在以下课程中
classdef ClassCar
properties (Constant)
% Car phyisical properties
m = 1630; % [kg]
R_rim = 14*.0254; % [m]
e_tire = .175*.55; % [m]
R_e = ClassCar.R_rim + ClassCar.e_tire; % <= HERE
% Car transmission properties
gearRatios = [3.154 1.925 1.281 .951 .756];
finalDrive = 3.05; %Rapport de differentiel
overallRatios = ClassCar.gearRatios * ClassCar.finalDrive;% <= HERE
end
end
我想要具有依赖于其他属性的组合属性(作为快捷方式)。即从instanciated对象(car = ClassCar)中检索
car.R_e
或
car.overallRatios
问题是R_e是R_rim和e_tire的函数。 使用(常量)属性,它可以,但问题是我希望这些属性不是常量,只是删除关键字会导致问题。
然后我尝试用方法帮助
classdef ClassCar
properties
% Car phyisical properties
m = 1630; % [kg]
R_rim = 14*.0254; % [m]
e_tire = .175*.55; % [m]
% Car transmission properties
gearRatios = [3.154 1.925 1.281 .951 .756];
finalDrive = 3.05; %Rapport de differentiel
end
methods (Static)
function value = R_e()
value = R_rim + e_tire; % <= HERE
end
function value = overallRatios()
value = gearRatios * finalDrive;
end
end
end
但即使使用关键字(静态)方法,我也会收到错误消息“未定义的函数或变量'R_rim'。”我尝试输入self.R_rim,ClassCar.R_rim,徒劳无功。
如何实现?这是最好的方法吗?如果是这样,如何访问对象的属性(如self.value那样)?
感谢。
答案 0 :(得分:4)
您正在寻找的是dependent properties。这些列为属性,但有自己的获取(或设置)值的方法:
classdef ClassCar
properties
R_Rim = 14*.0254;
e_tire = .175*.55;
end
properties (Dependent)
R_e
end
methods
function val = get.R_e(obj)
val = obj.R_rim + obj.e_tire;
end
end
end
答案 1 :(得分:1)
好的,我找到了答案:需要编写适当的专用函数。 我不知道方法的语法......
参见工作代码:
classdef ClassCar
properties
% Car phyisical properties
m = 1630; % [kg]
R_rim = 14*.0254; % [m]
e_tire = .175*.55; % [m]
% Car transmission properties
gearRatios = [3.154 1.925 1.281 .951 .756];
finalDrive = 3.05; %Rapport de differentiel
end
methods
function val = R_e(obj)
val = obj.R_rim + obj.e_tire;
end
function val = overallRatios(obj)
val = obj.gearRatios * obj.finalDrive;
end
end
end