【问题标题】:MATLAB Inheritance - What am I doing wrong?MATLAB 继承 - 我做错了什么?
【发布时间】:2013-08-31 07:10:07
【问题描述】:

我正在尝试一个简单的 MATLAB 继承示例。

我有 2 个文件 Man.m 和 Worker.m 如下:

classdef Man
    properties
        salary;
        age;
    end
    methods
        function obj=Man(s,a)
            obj.salary=s;
            obj.age=a;
        end
        function monthly_salary=FactorBy12(obj)
            monthly_salary=obj.salary/12;
        end

    end
end

classdef Worker < Man
    properties
        years_at_organization;
    end
    methods
        function obj=Worker(y,s,a)
            obj.years_at_organization=y;
            obj.salary=s;
            obj.age=a;
        end
        function bonus=BonusToBeGiven(obj)
            bonus=obj.years_at_organization;
        end
    end
end

我试图继承Worker 中的所有Man,但它不断向我抛出错误。 Man(5,6) 有效,但 Worker(5,6,7) 无效。 (Input argument "s" is undefined.)

如果我做一些简单的事情

classdef Woman < Man
end

根据this指南是有效的。

我做错了什么?

【问题讨论】:

  • 建议:您可能希望通过从 handle 继承来使 Man 类成为句柄类而不是值类:classdef Man &lt; handle

标签: matlab oop inheritance constructor


【解决方案1】:

由于superclass构造函数需要参数,你必须在子类中explicitly call它:

classdef Worker < Man
    properties
        years_at_organization;
    end
    methods
        function obj = Worker(y,s,a)
            obj = obj@Man(s,a);               % call ctor of superclass
            obj.years_at_organization = y;
        end
        function bonus = BonusToBeGiven(obj)
            bonus = obj.years_at_organization;
        end
    end
end

超类构造函数的implicit call 仅适用于默认 ctor(不期望参数)。一种解决方法是通过提供default values(如果适用)来允许这两种情况:

classdef Man
    ...
    methods
        function obj = Man(s,a)
            if nargin < 2, a = 20; end
            if nargin < 1, s = 1000; end
            obj.salary = s;
            obj.age = a;
        end
        ...
    end
end

请注意,如果要构建array of objects,则需要这样的默认构造函数:

>> m(5) = Man(5,3)
m = 
  1x5 Man array with properties:

    salary
    age

【讨论】:

  • 感谢 Amro。您知道 MATLAB 中的 OOP 指南吗? MATLAB 的官方文档非常小,我的问题中的指南非常薄弱。
  • @Inquest:我发现官方文档非常好且内容广泛,我主要从中学到了东西......那并在 Stack Overflow 上闲逛:)
猜你喜欢
  • 2012-03-09
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2015-04-23
  • 2017-06-07
  • 2010-12-14
相关资源
最近更新 更多