Add an item to a class

12 次查看(过去 30 天)
Astrik
Astrik 2016-8-25
评论: Astrik 2016-8-26
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?

采纳的回答

Guillaume
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
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.
Astrik
Astrik 2016-8-26
Exactly. It worked

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile 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!

Translated by