matlab - OOP中的Matlab私有/嵌套函数
问题描述
我有一个函数,它有几个子函数,一切都是句柄类的一部分。这可以通过以下来说明(私有函数没有循环依赖,有些东西依赖于对象):
function out = f1(obj, in)
out = f2(obj, f3(in * obj.Thickness));
end
function out = f2(obj, in)
out = f3(in / obj.NumLayers);
end
function out = f3(in)
out = in;
end
与文件夹f1.m
内的@MyClass
文件。
我决定将所有这些文件放在类中,并@MyClass
在制作最终包的过程中删除该文件夹(我现在就是那个时候)。
此时,类结构为
classdef MyClass < handle
properties
prop1
end
methods
function obj = MyClass(varargin) ...
function out = f1(obj, in)
end
methods (Access = private)
function out = f2(obj, in)
end
methods (Access = private, Static)
functions out = f3(obj, in)
end
end
一切都在MyClass.m
, f2 和 f3 是私有的,但显然可以看到类内的其他函数。我发现这有点问题,因为某些函数的名称略有相似(因为它们做的事情相似,尽管不是相同的东西)并且可能会误导维护代码的任何人——包括我以后。
嵌套函数是我简要考虑过的另一个选项,但是对于我的用例,我真的不喜欢“共享参数”位(这是那些嵌套函数的重点),因为对我来说这听起来很容易引入错误。
我在这里错过了任何更好的解决方案,还是应该坚持当前的私有功能?
解决方案
一种解决方案如下:
classdef name
properties
...
end
methods
function out = f1(obj, in)
out = f2(obj, f3(in * obj.Thickness));
end
end
end
function out = f2(obj, in)
out = f3(in / obj.NumLayers);
end
function out = f3(in)
out = in;
end
这使它们成为类私有的,但不是成员方法。我不确定这些私有函数是否可以访问该类的私有成员。
另一种方法是创建私有成员函数:
classdef name
properties
...
end
methods
function out = f1(obj, in)
out = f2(obj, f3(in * obj.Thickness));
end
end
methods (Access=private, Hidden=true)
function out = f2(obj, in)
out = f3(in / obj.NumLayers);
end
function out = f3(in)
out = in;
end
end
end
推荐阅读
- ios - (cloud firestore) vc1 在 doc 上有快照监听器,将 doc 数据传递给 vc2。vc2向doc写入数据,如何更新vc2上的数据?
- excel - 应用程序定义或对象定义错误 ('1004')
- java - 我如何在没有选择标签的情况下将选择 xpath 处理为 iframe
- reactjs - 未处理的拒绝(TypeError):无法读取未定义的属性“类别”
- c - 如何确定C中数组中子数组的起始索引
- nginx - Kubernetes NGINX 入口控制器 - 如果存在查询字符串,则路由不同
- php - 调用 PHP 中未定义的函数和数组键,即使它已明确定义?
- mongodb - 分组操作导致性能问题
- php - 为什么不使用 mysqli_Connect 连接 mysqli?
- excel - VBA自动过滤器实现中的多个不等于<>