【发布时间】:2017-08-29 17:32:39
【问题描述】:
我正在尝试实现类的CRTP 层次结构。我对基类感兴趣,以便在链中访问派生类的数据成员:
#include <iostream>
template <class Derived>
class A {
public:
void showv() {
std::cout << static_cast<const Derived*>(this)->v << std::endl;
}
};
template <class Derived>
class B : public A< Derived > {
typedef A<Derived> base;
friend base;
};
class fromA : public A<fromA> {
typedef A<fromA> base;
friend base;
protected:
int v = 1;
};
class fromB : public B<fromB>
{
typedef B<fromB> base;
friend base;
protected:
int v = 2;
};
int main()
{
// This runs ok
fromA derived_from_a;
derived_from_a.showv();
// Why doesn't the following compile and complains about the protected member?
fromB derived_from_b;
derived_from_b.showv();
return 0;
}
虽然第一个派生类 (fromA) 可以按预期编译和运行,但派生自A 的类的第二个派生类 (fromB) 却没有。
- 朋友声明未通过的原因是什么?
- 对解决方法有什么建议吗?
【问题讨论】:
-
为什么不创建虚函数 getV() 并在每个派生类中重写它,而不是和朋友一起玩?
-
friend我的friend不是我在 C++ 中的朋友。
标签: c++ polymorphism hierarchy friend crtp