Class implementation such that assignment x=MyObj does in fact x=MyObj.prop1

조회 수: 1 (최근 30일)
Let's say I have a class
classdef TestClass < handle
properties
prop1 = 7
prop2
end
methods
function method1(obj)
fprintf('prop1 is %g.', obj.prop1);
end
end
end
Now, when I do
Obj = TestClass;
x = Obj;
I want that the value of property prop1 is assigned to x, instead of the reference to Obj. So this assignment results to x=7.
And I would prefer to keep the class to be inherited from handle. But value class will also do.
I still would like to access prop2 as Obj.prop2 and call all the methods.
How this can be implemented in a custom class?
Thanks!
  댓글 수: 2
Matt J
Matt J 2022년 8월 4일
The similar behaviour the MATLAB's class string has.
I don't think so. You should probably demonstrate what you mean.
Oleg Iupikov
Oleg Iupikov 2022년 8월 4일
편집: Oleg Iupikov 2022년 8월 4일
I meant a case like
s = "abc"; s1 = s; s1
s1 = "abc"
so it displays the original string. But now I see that I was wrong. Perhaps it just overloads disp, or does a similar trick :) I removed that part from the question to not confuse people.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2022년 8월 4일
편집: Matt J 2022년 8월 4일
You can't have precisely what you have asked for, but you can do this,
classdef TestClass < handle
properties
prop1 = 7
prop2
end
methods
function method1(obj)
fprintf('prop1 is %g.', obj.prop1);
end
function out=double(obj) %converter
out=double(obj.prop1);
end
function out=single(obj) %converter
out=single(obj.prop1);
end
end
end
and then,
>> Obj=TestClass
Obj =
TestClass with properties:
prop1: 7
prop2: []
>> x=zeros(1,3)
x =
0 0 0
>> x(3)=Obj
x =
0 0 7
  댓글 수: 1
Oleg Iupikov
Oleg Iupikov 2022년 8월 4일
Unfortunatelly, for this we already need to have a variable of class double or single, and do an indexed assignment.
In any case, thanks for your time and answer!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by