【问题标题】:How do I access a superclass's constant property within Matlab?如何在 Matlab 中访问超类的常量属性?
【发布时间】:2013-03-10 06:40:15
【问题描述】:

我有一个简单的类结构,如下所示:

classdef super < hgsetget
    properties(Constant = true, Access = private)
        PROP1 = 1;
        PROP2 = {2 [3 4] [5 6]};
    end

    methods
        function self = super()
            // Constructor code here
            // ...
        end
    end
end

然后被这样的子类继承。

classdef sub < super
    properties
        PROP3 = 7;
    end

    methods
        function self = sub()
            // Subclass constructor here
            // ...
            self = self@super();
            test = self.PROP1; // I don't appear to have access to PROP1 from Super

        end
    end
end

我的问题是当我尝试访问超级的属性PROP1PROP2 时,我似乎无法访问:

类 sub 没有合适的方法、属性或字段 PROP1。

有没有办法在 Matlab 中访问 super 的属性?

【问题讨论】:

    标签: oop matlab inheritance subclass superclass


    【解决方案1】:

    在超类super 中设置属性属性为

    properties(Constant = true, Access = protected)
    

    来自the documentation 的访问属性决定了哪些代码可以访问这些属性:

    • public — 无限制访问
    • protected — 从类或子类中的方法访问
    • private - 只能通过类方法访问(不能从子类访问)

    【讨论】:

      【解决方案2】:

      您将属性定义为private,它们不会被继承。

      请改用Access = protected

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        相关资源
        最近更新 更多