Overloading subsasgn without breaking class privacy rules

2 vues (au cours des 30 derniers jours)
Matthew M.
Matthew M. le 16 Juin 2011
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?

Réponse acceptée

Daniel Shub
Daniel Shub le 16 Juin 2011
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 commentaire
Matthew M.
Matthew M. le 16 Juin 2011
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by