Add an item to a class
12 ビュー (過去 30 日間)
古いコメントを表示
I have two classes defined: library and book. The library has name and books. Book has a name and and an author. I have a method in library class which adds book to the library. They are as follows
classdef library
properties
name
books=struct('author',{},'title',{})
end
methods
function self=library(val1)
self.name=val1;
end
function addbook(self,item)
self.books(end+1)=item;
end
end
end
And the book class is
classdef book
properties
author
title
end
methods
function self=book(val1,val2)
self.author=val1;
self.title=val2;
end
end
end
Now I define
lib1=library('Leib')
and
book1=book('A','T')
When I want to add this book to my library using
lib1.addbook(book1)
I get the error
_Assignment between unlike types is not allowed.
Error in library/addbook (line 11) self.books(end+1)=item;_
Anyone can hepl me understand my mistake?
0 件のコメント
採用された回答
Guillaume
2016 年 8 月 25 日
struct and class are two completely different types even if they have the same fields/properties. You have defined the books member of your library class as an array of structures. You cannot add class objects to an array of structure. Only more structures with the same field.
The solution, is to declare your books member as an empty array of book objects:
classdef library
properties
name
books = book.empty
end
%...
3 件のコメント
Sean de Wolski
2016 年 8 月 26 日
編集済み: Sean de Wolski
2016 年 8 月 26 日
This is because your class is a value class not a handle class.
You can either have the library class inherit from handle (I'd recommend this!)
classdef library < handle
Or you need to passback an output from addBook.
lib = addBook(lib,book1)
The code analyzer is telling you about this with the orange underline on self above.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Construct and Work with Object Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!