1

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

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

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成员,因为它必须由基类修改。我怎样才能产生预期的行为?

4

3 回答 3

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;
};
于 2013-03-17T10:52:13.040 回答
4

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

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

    public:
         int getValue() {return value;}

    private:
         int value;
}

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

于 2013-03-17T10:52:34.147 回答
0

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

于 2014-01-13T19:22:25.283 回答