Overloading subsasgn without breaking class privacy rules
1 次查看(过去 30 天)
显示 更早的评论
I'm writing a simple class to handle three-vectors - just an array of three numbers. The actual array is stored in the 'Data' property, which is (Access = 'private'). I want to access the values using parenthesis indexing only, so I'm overloading subsasgn. I'm also trying to use the xUnit Test Framework, so I'm trying to keep fairly careful track of the error messages. Here's the subsasgn function I've written for the Vector3 class:
function V = subsasgn(V,s,b)
switch s(1).type
case '()'
V = Vector3(builtin('subsasgn',V.Data,s,b));
case '{}'
error('Vector3:subsasgnCell','cell assignment not supported')
case '.'
switch s(1).subs
case 'Data'
error('Vector3:setProhibited','... not allowed')
otherwise
error('Vector3:subsasgnDot','dot assign not allowed')
end
end
end
Here's where it gets weird: If I define a Vector3 variable at the Command Line, and I then try to assign to the 'Data' property from the Command Line, I get the expected error message:
>> V = Vector3([1 -45 7.9])
1 -45 7.9
>> V.Data = [2 4 9]
??? Error using ==> ...Vector3.subsasgn...
... not allowed
But if I define a function and try to do the same thing, like...
function out = weirdo(V)
V.Data = [2 4 9];
out = V;
end
and call that function from the command line:
>> V = Vector3([1 -45 7.9])
1 -45 7.9
>> W = weirdo(V)
2 4 9
>> class(W)
ans =
Vector3
I've tested it a couple different ways, and basically it seems that when I try setting the private property from the Command Line it fails as designed, but when I set it within a function it succeeds when it shouldn't.
What am I doing wrong?
0 个评论
采纳的回答
Daniel Shub
2011-6-16
My guess is that you are saving weirdo in a location such that it is becoming a method of the class. For good or for bad, methods of a class call the builtin subasgn and subsref functions and not the overloaded functions.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!