c ++中的基类中的受保护字段的问题 [英] Problem with protected fields in base class in c++

查看:80
本文介绍了c ++中的基类中的受保护字段的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,说 BassClass ,有一些字段,我使它们受保护,以及一些纯虚函数。然后派生类,如 DerivedClass ,如 class DerivedClass:public BassClass 。应该不是DerivedClass从BassClass继承受保护的字段?当我试图编译DerivedClass时,编译器抱怨DerivedClass没有任何这些字段,这里有什么错误?
感谢

I have a base class, say BassClass, with some fields, which I made them protected, and some pure virtual functions. Then the derived class, say DerivedClass, like class DerivedClass : public BassClass. Shouldn't DerivedClass inherit the protected fields from BassClass? When I tried to compile the DerivedClass, the compiler complains that DerivedClass does NOT have any of those fields, what is wrong here? thanks

推荐答案

如果 BassClass code> DerivedClass 是模板,您要从 DerivedClass 访问的 BassClass c>未指定为依赖名称,它将不可见。

If BassClass (sic) and DerivedClass are templates, and the BassClass member you want to access from DerivedClass isn't specified as a dependent name, it will not be visible.

例如

template <typename T> class BaseClass {
protected: 
    int value;
};

template <typename T> class DerivedClass : public BaseClass<T> {
public:
    int get_value() {return value;} // ERROR: value is not a dependent name
};

要获得访问权限,您需要提供更多信息。例如,您可以完全指定成员的名称:

To gain access you need to give more information. For example, you might fully specify the member's name:

    int get_value() {return BaseClass<T>::value;}

或者你可能会明确表示你是指一个类成员:

Or you might make it explicit that you're referring to a class member:

    int get_value() {return this->value;}

这篇关于c ++中的基类中的受保护字段的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆