Updating property of an Object without creating new object

22 ビュー (過去 30 日間)
Martyn
Martyn 2015 年 3 月 15 日
コメント済み: Arvind 2022 年 12 月 7 日
Hi
I’m writing a class for the first time, and got an issue I don’t understand.
To simplify the problem, assume my class is as follows:
========================================
classdef testClass
properties
count
end
methods
function obj = testClass
obj.count = 1;
end
function obj = increment(obj)
obj.count = obj.count + 1;
end
end
end
========================================
>> x = testClass;
This creates the class and sets x.count to 1 as required
I then want to increment the value of x.count I was hoping that:
>> x.increment;
would add 1 to count. But it simply creates a new object (‘ans’), where ans.count == 2
I can of course write,
>> x = x.increment;
But that feels illogical.
I've tried various things, and Googled the type of problem, but have found a solution. So any guidance would be welcome.
Thanks. Martyn
  2 件のコメント
Dr. ghada farouk
Dr. ghada farouk 2018 年 12 月 29 日
編集済み: Walter Roberson 2018 年 12 月 29 日
you should write
x=x.increment(x);
Walter Roberson
Walter Roberson 2018 年 12 月 29 日
Dr. ghada farouk: writing that is not needed if you use a handle class.

サインインしてコメントする。

採用された回答

Sebastian Castro
Sebastian Castro 2015 年 3 月 15 日
編集済み: Sebastian Castro 2015 年 3 月 15 日
When you create a class in MATLAB, it is by default a value class. If you want to update objects by reference, you should make this a handle class by changing the first line to:
classdef testClass < handle
EDIT: Also, you wouldn't necessarily need output arguments for the methods of the handle class.
Check out this documentation page for the differences between value classes and handle classes.
- Sebastian
  4 件のコメント
Redouane Bouchou
Redouane Bouchou 2020 年 4 月 10 日
Thank you
Arvind
Arvind 2022 年 12 月 7 日
thanks a lot.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeHandle Classes についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by