'When constructing an instance of class 'storage', the constructor must preserve the class of the returned object."
조회 수: 17 (최근 30일)
이전 댓글 표시
This class displays the correct answer followed by the error message 'When constructing an instance of class 'storage', the constructor
must preserve the class of the returned object." I would like to return the stringLength given a stringInput not necessarily using the display function. (Other community responses related to this topic have not been clear to me.) Thank you!
classdef storage
properties
stringInput
end
methods
function stringLength = storage(stringInput)
stringLength = strlength(stringInput)*2;
disp(num2str(stringLength));
end
end
end
I tested as follows:
>> stringInput = 'Hello world!';
>> stringLength = storage(stringInput)
24
When constructing an instance of class 'storage', the constructor
must preserve the class of the returned object.
댓글 수: 0
채택된 답변
Walter Roberson
2022년 2월 2일
function stringLength = storage(stringInput)
is your constructor. It must return the constructed object.
In the simple case of a non-derived class, the object just pops into existence in the variable named on the left side of the = of the constructor method. In this case, that means that inside the storage method, the variable stringLength will hold the constructed object of class storage . You can then potentially modify that variable stringLength but when you do so you must do so in a way that the class storage is preserved.
It looks to me as if you are trying to create a constructor that stores the input character vector and immediately return... twice its length? (Perhaps representing number of bytes of storage ?) You cannot do that in one shot: you need to return the object and then you take the strlength of the stored object as a separate operation. You will want to use a different method for that, perhaps named stringLength
classdef storage
properties
stringInput
end
methods
function obj = storage(stringInput)
obj.stringInput = stringInput;
end
function len = stringLength(obj)
len = strlength(obj.stringInput)*2;
end
end
end
test with
obj = storage('Hello world!')
obj.stringLength
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Properties에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!