如何使派生类的成员为只读

How to make a member readonly for derived classes?

本文关键字:成员 只读 何使 派生      更新时间:2023-10-16

给定一个具有受保护成员的抽象基类,如何仅对派生类提供读访问?

为了说明我的意图,我提供了一个最小的例子。这是基类。
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成员,因为它必须由基类修改。我怎样才能产生预期的行为?

通常的方法是在基类中创建成员private,并提供protected访问器:

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

由于protected成员在派生类中是可见的,如果您希望该成员在派生类中是只读的,您可以将其设为private,并提供getter函数。

class Base {
public:
    Base();
    virtual Base();
    public:
         int getValue() {return value;}
    private:
         int value;
}

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

继承的最佳实践指南应该始终将成员变量设为私有,而将访问器函数设为公共。如果你有只希望从派生类调用的公共函数,这意味着你正在编写意大利面条式的代码。