Overloading subsasgn without breaking class privacy rules
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Daniel Shub
il 16 Giu 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Identification in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!