필터 지우기
필터 지우기

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