How to set a private property

30 次查看(过去 30 天)
Ok so I'm used to c++, and in c++ a private variable (property in matlab) can be accesed by every method in that class, I'm trying to do the same here in the constructor, I want it to establish some default values if no arguments have been provided, this is my code:
classdef modulo
properties (Access=private)
A
B
R
actuadores
end
methods
function obj=modulo(BB,Actuadores)
if nargin<1
obj.B=[0,0,0];
end
if nargin<2
obj.actuadores=0;
else
obj.B=BB;
obj.actuadores=Actuadores;
end
end
end
end
But then, I do
smth=modulo
or
smth=modulo([4 3 2],5)
and I expect:
smth =
modulo with properties:
A: []
B: [0 0 0]
R: []
actuadores: 0
or
smth =
modulo with properties:
A: []
B: [4 3 2]
R: []
actuadores: 5
But instead I get:
smth =
modulo with no properties.
It works as intended when I don't set any private attributes, but how can I access those properties if I want them to be private?

采纳的回答

Walter Roberson
Walter Roberson 2017-8-4
Look at the description of Access:
"Use Access to set both SetAccess and GetAccess to the same value. "
So setting Access to private sets GetAccess to private.
Then in the description of GetAccess:
"MATLAB does not display in the command window the names and values of properties having protected or private GetAccess or properties whose Hidden attribute is true."
Therefore what you are seeing is the designed behavior for having set Access to 'private': you have told it not to display those properties when the object is displayed.
  4 个评论
Walter Roberson
Walter Roberson 2017-8-4
Right, you just cannot see the properties from outside the class objects. You cannot get() private properties from outside the class objects either. From outside the class objects all you can do is bypass the security by using struct() to look at the properties.
Javi Cansa
Javi Cansa 2017-8-4
Thank you, I simply created a get method myself for debug purposes, so whenever I want to see, say, B for example, I just write:
smth.get('B')
and it returns whatever is stored in B.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 App Building 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by