如何使派生类的成员为只读
How to make a member readonly for derived classes?
给定一个具有受保护成员的抽象基类,如何仅对派生类提供读访问?
为了说明我的意图,我提供了一个最小的例子。这是基类。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;
}
这样你仍然可以改变基类中的值,并且它在子类中是只读的。
继承的最佳实践指南应该始终将成员变量设为私有,而将访问器函数设为公共。如果你有只希望从派生类调用的公共函数,这意味着你正在编写意大利面条式的代码。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- C++/QT:使用指向私有成员的常量指针作为只读数据共享
- 如何修复只读对象中成员的错误分配?
- 当我在C++中调用 struce 的只读静态成员时,线程是否安全
- 非常量调用 const 成员函数失败,只读位置C++
- 使用 std::map 时只读成员的错误递减
- 类的只读成员变量
- 错误:在只读对象中分配成员
- 将公共成员设置为只读
- 只读类成员C++
- 在只读对象中分配成员 '
- 在C++中创建只读(公共)类成员
- 通过只读迭代器公开成员数据
- 如何使派生类的成员为只读
- 全局变量是只读的,并在 openmp 中"false sharing"写入私有类成员