如何为派生类创建一个只读成员?

dan*_*jar 1 c++ inheritance member readonly

给定一个带有受保护成员的抽象基类,如何只为派生类提供读访问权限?

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

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

这是派生类.

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

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

sya*_*yam 8

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

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