我正在使用CRTP,我在访问派生类的受保护成员时遇到问题。
这是示例,靠近我的代码:
template< typename Self>
class A {
public:
void foo( ) {
Self s;
s._method( s); //ERROR, because _method is protected
}
protected:
virtual void _method( const Self & b) = 0;
};
class B : public A< B> {
protected:
void _method( const B & b) {}
};
我明白了,我必须使用朋友关键字。但我无法理解在课堂上把它放在哪里 A&lt;自&GT; 即可。我知道我可以在 B 中公开 void _method(const B&amp; b),但我不想这样做。使用 B 中的任何关键字对我来说都是不可能的!
答案 0 :(得分:2)
我刚刚找到了解决方案。谢谢你的回答。我只需要改变这一行:
s._method( s); //ERROR, because _method is protected
到
( ( A< Self> &) s)._method( s);
答案 1 :(得分:0)
template< typename Self>
class A {
public:
void foo( ) {
Self s;
s._method( s); //ERROR, because _method is protected
}
protected:
virtual void _method( const Self & b) = 0;
};
template< typename Self>
class B : public A< Self> {
protected:
void _method( const Self & b) {}
};
这样做;在你的A类中,_method是纯虚拟的,你必须在B类中重写它。