是否有可能以某种方式允许 parent 访问受 child 保护的成员?
template <class T>
class B {
public :
void print()
{
cout << T::a << T::b << endl;
}
};
class C : public B<C>
{
protected :
static int a;
static int b;
public :
C() {
print();
}
};
这对我在没有多态性(虚拟)的情况下继承多个对象很有用。有什么建议吗??
编辑:
我找到了下面建议的两个解决方案::
- 将B作为 friend 类,
- CRTP
还有几点需要考虑,在使用 CRTP 时确保您使用内联,否则它不会使其更快(但可能会发生代码膨胀)。不要忘记使 B 构造函数 protected (在静态派生数据访问的情况下)。
CRTP也可以用于不从基类向派生类传递静态常量数据(virtual static const)
现代编译器使用一个称为去虚拟化的概念,我认为现在大多数编译器中都有。
最佳答案
This will be useful for me to inherit multiple objects without polymorphism(virtual).
这是一个众所周知的模式,又名静态多态性。
CRTP使用 static_cast<T*>(this)
通常引用派生类函数:
template <class T>
class B {
public :
void print()
{
cout << static_cast<T*>(this)->a << static_cast<T*>(this)->b << endl;
// ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
}
};
I need to somehow allow parent to access child protected data, is it possible?
当然可以。这些需要是 public
T
的成员, 或者你需要制作 B<T>
一个friend
类T
:
class C : public B<C>
{
friend class B<C>;
// ^^^^^^^^^^^^^^^^^^
protected :
static int a;
static int b;
public :
C() {
print();
}
};
friend
声明仍然保留 class C
的封装, 同时打开对 class B<T>
中声明的特定接口(interface)的访问.
关于c++ - 家长访问 child 私有(private)/ protected ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898554/