【问题标题】:How to make a member readonly for derived classes?如何使派生类的成员只读?
【发布时间】:2013-03-17 10:48:31
【问题描述】:

给定一个带有受保护成员的抽象基类,我怎样才能只提供对派生类的读取访问权限?

为了说明我的意图,我提供了一个最小的示例。这是基类。

class Base
{
public:
    virtual ~Base() = 0;
    void Foo()
    {
        Readonly = 42;
    }
protected:
    int Readonly;                 // insert the magic here
};

这是派生类。

class Derived : public Base
{
    void Function()
    {
        cout << Readonly << endl; // this should work
        Readonly = 43;            // but this should fail
    }
};

不幸的是,我不能使用const 成员,因为它必须可由基类修改。我怎样才能产生预期的行为?

【问题讨论】:

  • 除了让它成为一个常数,你不能。
  • 能否将其设为私有并仅提供受保护的 getter 方法?
  • 你应该定义一个构造函数来初始化Readonly

标签: c++ inheritance readonly member


【解决方案1】:

通常的做法是让你的成员private 在基类中,并提供一个protected 访问器:

class Base
{
public:
    virtual ~Base() = 0;
    void Foo()
    {
        m_Readonly = 42;
    }
protected:
    int Readonly() const { return m_Readonly; }
private:
    int m_Readonly;
};

【讨论】:

  • 比我的回答好多了,+1。
  • 谢谢,有时候就是这么简单!
  • 删除inline关键字;它是inline,因为它是在声明中定义的。
【解决方案2】:

由于受保护的成员在派生类中是可见的,如果您希望该成员在派生类中是只读的,您可以将其设为私有,并提供一个getter函数。

class Base {
public:
    Base();
    virtual Base();

    public:
         int getValue() {return value;}

    private:
         int value;
}

这样你仍然可以更改基类中的值,并且它在子类中是只读的。

【讨论】:

    【解决方案3】:

    继承的最佳实践准则应该是始终将成员变量设为私有,并将访问器函数设为公开。如果您有只希望从派生类调用的公共函数,则意味着您正在编写意大利面条式代码。 (来源:Meyer's Effective C++ item 22)

    【讨论】:

    • 那么protected 关键字是什么? ;)
    猜你喜欢
    • 2019-11-13
    • 2012-03-05
    • 2017-12-02
    • 2018-11-30
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    相关资源
    最近更新 更多