Add an item to a class
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Astrik
el 25 de Ag. de 2016
Comentada: Astrik
el 26 de Ag. de 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?
0 comentarios
Respuesta aceptada
Guillaume
el 25 de Ag. de 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 comentarios
Sean de Wolski
el 26 de Ag. de 2016
Editada: Sean de Wolski
el 26 de Ag. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!