Add an item to a class

6 views (last 30 days)
Astrik
Astrik on 25 Aug 2016
Commented: Astrik on 26 Aug 2016
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?

Accepted Answer

Guillaume
Guillaume on 25 Aug 2016
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 Comments
Sean de Wolski
Sean de Wolski on 26 Aug 2016
Edited: Sean de Wolski on 26 Aug 2016
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 on 26 Aug 2016
Exactly. It worked

Sign in to comment.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!