'When constructing an instance of class 'storage', the constructor must preserve the class of the returned object."
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Dora Velcsov
il 2 Feb 2022
Commentato: Dora Velcsov
il 6 Feb 2022
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 Commenti
Risposta accettata
Walter Roberson
il 2 Feb 2022
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Properties in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!