Clarification about modifying properties in handle class

1 回表示 (過去 30 日間)
Bandar
Bandar 2021 年 7 月 20 日
回答済み: Steven Lord 2021 年 7 月 21 日
Take a look at the following class
classdef Counter < handle
properties
count
end
methods
function this = Counter(x)
if nargin == 1
this.count = x;
end
end
function increment(this)
this.count = this.count + 1;
end
end
end
In the constructor, if the argument is zero, count is initliazed according to its value in properties block. In the preceding code, count is empty. It is interesting to notice that in this particular case, calling increment() has no effect on incrementing count. I have to explicitly initializing it with any value in order to make `increment()` works. Any suggestions why I need to explicitly initialize properties?

採用された回答

Steven Lord
Steven Lord 2021 年 7 月 21 日
In the preceding code, count is empty.
That is correct, the default value for that propery is the 0-by-0 empty double array [] as stated in the "Property Default Values" section of this documentation page.
calling increment() has no effect on incrementing count
That is also correct.
x = []
x = []
y = x + 1
y = []
The 1 is scalar "expanded" to be a 0-by-0 and a 0-by-0 plus a 0-by-0 results in a 0-by-0.
Any suggestions why I need to explicitly initialize properties?
Because you don't want the default value for that property to be empty in this case.
By the way, despite you mentioning "handle class" in the subject of this post, this behavior holds for value classes as well.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by