'When constructing an instance of class 'storage', the constructor must preserve the class of the returned object."

14 次查看(过去 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.

采纳的回答

Walter Roberson
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 CenterFile Exchange 中查找有关 Properties 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by