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?

回答(1 个)

Daniel Shub
Daniel Shub 2012-10-11
I think you would need to overload disp for the struct class.
  2 个评论
Matt J
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 CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by