oop - 重载的 horzcat() 如何工作?

标签 oop matlab overloading

我正在编写一个 Matlab 类,它实现自定义串联,以便向用户呈现一个干净、富有表现力的界面。与内置函数不同,重载的 horzcat() 的结果——例如——应该是根据类语义设置的标量对象。但是,我不再确定哪些规则适用于重载函数......

说明该问题的类是:

classdef A < handle
        properties
                k;
        end;

        methods
                function obj = A(varargin)
                        if nargin == 0
                                obj.k = 0;
                        else
                                obj.k = varargin{1};
                        end;
                end;

                function obj = horzcat(obj1, varargin)
                        fprintf('1st arg is %s.\n', class(obj1));
                        if nargin > 1
                                fprintf('2nd arg is %s.\n', class(varargin{1}));
                        end;
                        obj = obj1; % Not important
                end;
        end;
end

现在,当使用小脚本测试此类时:

% Please don't run this is you have valuable
% data in your base workspace.
clear classes;
clc;

a = A('dummy');
b = [-1, a]; % Should fail

输出是:

1st arg is double.
2nd arg is A.

这令人惊讶,因为第一个参数是 double ,即应该调用内置的 horzcat() ,随后抛出有关类型不匹配或其他问题的异常。据我了解,第一个参数的类型决定将调用哪个重载函数(好吧,我们将自己限制为非静态方法)。代码在R2011b/Linux和R2012a/Windows上测试,结果相同。

所以,这就是我的问题:调用重载方法的实际规则是什么? Matlab 文档没有解释上述结果,我希望避免基于我对语言工作原理的幻想来开发代码。

预先感谢您的意见。

最佳答案

我认为 MATLAB 的文档对此非常清楚:

来自here :

MATLAB uses the dominant argument to determine which version of a function to call. If the dominant argument is an object, then MATLAB calls the method defined by the object's class, if there is one.

来自 here有关主导论点的更多信息:

The dominant argument in a method's argument list determines which version of the method or function that the MATLAB runtime calls. Dominance is determined by the relative precedences of the classes of the arguments. In general, user-defined classes take precedence over built-in MATLAB classes. Therefore, the left most argument determines which method to call. However, user-defined classes can specify the relative dominance of specific classes.

关于oop - 重载的 horzcat() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15958616/

相关文章:

c++ - 为什么我的日志在 std 命名空间中?

c++ - 复制构造函数不起作用?

java - 如何访问对象的这个参数

c# - 如何使类受继承保护?

Java 删除与泛型重载(不重写)

c++ - 选择成员函数而不是成员函数定义中具有相同名称的函数

c++ - 制作动态对象数组问题?

java - 在 Java 中从 JMatio 库初始化稀疏矩阵

image - 删除背景并将鹿作为前景?

matlab - 有没有办法在 matlab 的单元格模式下调用子函数?