Pass data to an instance of a class outside the constructor

Dear all,
I am currently working on a class that is associated with various methods. One of the methods (function) produces some additional data associated with the instance of the class. This data should be available if I call the function with the same instance again, but it should not be available (since it eats memory) if I have never called that function. Can anybody give a hint, how I could pass this data to the instance without that it was generated in the constructor?
Hope I made myself clear. I am still new to OOP and not too familiar with the terminology.
Best regards, Anon

回答 (1 件)

Sean de Wolski
Sean de Wolski 2012 年 7 月 11 日

1 投票

obj = object_of_some_class(pi,exp(1));
obj.some_property = that_value; %set that other property here

7 件のコメント

Anon
Anon 2012 年 7 月 11 日
Thanks, Sean. Right now, I don't have access to matlab, so I cannot try. But does the second line work from within a function? Or only in the workspace.
Anon
Anon 2012 年 7 月 12 日
Hi Sean, as far as I can see, your approach only works when you access obj from the workspace. If I call
obj.some_property = that value
from a class method I receive following error
No public field IX exists for class MyClass.
If I define IX in the property list, the error doesn't show up, but the values assigned to property IX in the function will not be stored in the object instance in the workspace. Any ideas? Help is much appreciated.
Sean de Wolski
Sean de Wolski 2012 年 7 月 12 日
Is it a handle class?
Anon
Anon 2012 年 7 月 12 日
編集済み: Anon 2012 年 7 月 13 日
No, it isn't. It is a value class.
The basic idea is that the user should not be bothered with an additional function that adds values to the instance of the object. So instead of doing something like this:
obj = object_of_some_class(pi,exp(1));
obj = do_additional_calcs_required_to_run_fun(obj);
A = fun(obj);
I would like a work flow like
obj = object_of_some_class(pi,exp(1));
A = fun(obj);
where fun is capable to change the instance obj in the workspace. This action should be comparable to what the function assignin does.
Anon
Anon 2012 年 7 月 13 日
I just made some changes to my above comments.
Sean de Wolski
Sean de Wolski 2012 年 7 月 13 日
Then make it a handle class! This is exactly the reason for handle classes, i.e: you pass the handle to the object around and allow other functions to modify it via its handle.
Anon
Anon 2012 年 7 月 13 日
I see, there is still a lot to learn. A quick reading of the difference of handle and value classes reveals that handle classes might be an elegant solution to my problem. Thanks for your help!

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

カテゴリ

ヘルプ センター および File Exchange で Construct and Work with Object Arrays についてさらに検索

タグ

質問済み:

2012 年 7 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by