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?

采纳的回答

Daniel Shub
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.
  1 个评论
Matthew M.
Matthew M. 2011-6-16
I thought I had gotten around that by putting my unit-testing functions in a subdirectory of the class folder that was not on the MATLAB path, but I guess you can't do that. When I pulled them out of there they work as expected. Rookie mistake. Thanks for the tip.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by