使用 CRTP 访问派生类的受保护成员
Accessing protected members of derived class with CRTP
>我正在使用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类<自我>自我>的什么地方。我知道我可以在 B 中公开 void _method( const B &B),但我不想这样做。在 B 中使用任何关键字对我来说也是不可能的!
我刚刚找到了解决方案。感谢您的回答。我只需要更改此行:
s._method( s); //ERROR, because _method is protected
自
( ( A< Self> &) s)._method( s);
它有效!http://ideone.com/CjclqZ
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类中覆盖它。
相关文章:
- C++:无法访问声明的受保护成员
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 同一模板类但模板类型的受保护成员
- 派生类无法访问基类的受保护成员
- 继承期间受保护成员的皮条
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- 是否可以基于私有/受保护成员分配类枚举?
- 依赖模板基础的受保护成员
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 将对象强制转换为派生类以访问父类的受保护成员
- 使从一个基类派生的类能够使用继承的受保护成员
- 派生类如何使用基类的受保护成员
- 访问派生类C++中的受保护成员
- 访问基类的受保护成员
- 如何访问多个继承类中的受保护成员
- 如何从另一个类的基类访问派生类中的受保护成员
- 无法访问派生类中的基本受保护成员!(在虚函数中)
- 如何通过派生类访问基类的受保护成员?
- 如果孩子不需要父母班级的所有受保护成员,这是不好的班级设计吗?