Override how the value of a user defined class is displayed when it is a field of a structure
조회 수: 2 (최근 30일)
이전 댓글 표시
I have created my own class to act like an enumerated type. I haver overridden the method disp() so when a variable containing that type is displayed in the Command Window it shows something meaningful (specifically, the name of that enumerated value.)
classdef MyEnumeratedType
properties(Constant)
ENUMVAL1 = MyEnumeratedType(1, 'ENUMVAl1');
ENUMVAL2 = MyEnumeratedType(2, 'ENUMVAL2');
ENUMVAL3 = MyEnumeratedType(3, 'ENUMVAL3');
end
properties(Access=private)
ordinal
name
end
methods(Access=private)
function this = MyEnumeratedType(ord, name)
this.ordinal = ord;
this.name = name;
end
end
methods
function disp( this )
disp(this.name);
end
end
end
So when I assign it to a variable in the command window, I get the desired output:
>> x = MyEnumeratedType.ENUMVAL2
x =
ENUMVAL2
So far so good. BUT when I assign a value of type MyEnumeratedType to the field of a structure, the display of that structure doesn't display the value, but only tells me that I have a value of type MyEnumeratedType.
>> mystruct.field1 = 42
mystruct =
field1: 42
>> mystruct.field2 = MyEnumeratedType.ENUMVAL3
mystruct =
field1: 42
field2: [1x1 MyEnumeratedType]
How do I get the value of field2 to show up like it does for the double value in field1?
Question also posted at StackOverflow at http://stackoverflow.com/questions/12846290/override-how-the-value-of-a-user-defined-class-is-displayed-when-it-is-a-field-o
댓글 수: 1
답변 (1개)
Daniel Shub
2012년 10월 11일
I think you would need to overload disp for the struct class.
댓글 수: 2
Matt J
2012년 10월 11일
You can create your own directory @struct and put a revised definition of the display() method in there. You can also call the builtin version of struct/display using the BUILTIN function to help you overload it. Seems like a lot of work to me, however.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!