matlab - Matlab在构造函数中无法更改类的参数
问题描述
我正在调用一个函数来更改其构造函数中的类的参数,但是,我无法更改这些值。这是一个错误还是故意的?
在下面的示例中,我在构造函数中调用函数“calculateCalculatedProperties()”。“calculateCalculatedProperties()”调用“Velocity()”和“Length()”函数来设置速度和长度属性的新值。但是,构造函数(对象实例)的最终产品属性没有改变。
classdef piping
%PIPING Summary of this class goes here
% Detailed explanation goes here
properties
flowRate
diameter
startLocation location
endLocation location
end
methods
function self = piping(flowRate, diameter, startLocation, endLocation)
self.flowRate = flowRate;
self.diameter = diameter;
self.startLocation = startLocation;
self.endLocation = endLocation;
self.calculateCalculatedProperties();
end
function self = calculateCalculatedProperties(self)
fprintf("hey")
self.Velocity();
self.Length();
end
function self = Velocity(self)
self.velocity = self.flowRate / (pi * self.diameter^2 / 4);
end
function self = Length(self)
self.length = location.calculateDistance(self.startLocation,self.endLocation) ;
fprintf("hey this is lengthhhh")
self.flowRate = 10000000;
end
end
properties % Calculated properties
velocity
length
end
end
解决方案
这里的问题是您使用的是值类,而不是句柄类。请注意,在您的 Velocity 方法中,您将返回“self”的实例,在值类中,这些方法调用返回一个单独的对象,该对象在此代码中被忽略。
话虽如此,有两种可能的解决方案:
捕获值对象的输出并返回最终的修改对象。
function self = piping(flowRate, diameter, startLocation, endLocation) % ... self = self.calculateCalculatedProperties(); end function self = calculateCalculatedProperties(self) fprintf("hey") self = self.Velocity(); self = self.Length(); end
使用句柄类创建一个可变对象。
classdef piping < handle % ... end
有关详细信息,请参阅句柄和值类的比较。
推荐阅读
- android - glide 加载资源失败,刷新后成功
- java - ActiveMQ artemis - 如何制作监听进程
- .htaccess - .htaccess rewriterule bad flag delimiters referer
- tensorflow - 禁止 ML.NET 控制台输出
- bash - 无法将作业 ID 传递给 SLURM
- python - 有没有办法将不同的函数应用于数据帧的每一行,其中特定列中的 str 值决定函数?
- java - 我想检查堆栈集合中的每个元素并反向打印。打印输出应该按升序打印每个元素
- flutter - 如何将 whatsapp 聊天导出到我的 Flutter 应用程序?
- ballerina - 在 Ballerina lang 的模块中创建服务
- java - 如何重构返回不同类型列表的方法