2013-03-17 85 views
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构件。我怎样才能产生预期的行为?

+0

除了使它成为一个常数,你不能。 – 2013-03-17 10:50:20

+2

你可以让它私人,只是提供一个受保护的getter方法? – 2013-03-17 10:51:28

+1

您应该定义一个构造函数来初始化'Readonly'。 – 2013-03-17 10:54:26

回答

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; 
}; 
+0

比我的回答+1好多了。 – jrok 2013-03-17 10:52:54

+0

谢谢,有时它很简单! – danijar 2013-03-17 10:53:29

+1

删除'inline'关键字;它是通过在声明中定义而“内联”的。 – 2013-03-17 10:53:32

4

由于保护成员在派生类中可见,如果你想成员是在派生类中只读,您可以将其设为私有,并提供getter函数。

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

    public: 
     int getValue() {return value;} 

    private: 
     int value; 
} 

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

0

继承的最佳实践指导方针应该始终使成员变量保持私有,并将访问者函数公开。如果你有只需要派生类调用的公共函数,这意味着你正在编写意大利面代码。 (来源:迈尔有效的C++项目22)

+0

那么受保护的关键字是什么? ;) – danijar 2014-01-14 08:23:12

相关问题