我正在嘗試實現CRTP類的層次結構。我對基類能夠訪問一個派生類向下該鏈的數據成員:爲什麼不編譯以下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
)編譯和運行正如所料,該第二(fromB
),從派生自A
的類派生,不。
- 朋友聲明沒有引導到什麼原因?
- 有關解決方法的任何建議?
爲什麼不創建虛函數getV()並在每個派生類中重寫它而不是與朋友的遊戲? –
我朋友的'朋友'不是我在C++中的朋友。 – Jarod42