Problem with protected fields in base class in c++

僤鯓⒐⒋嵵緔 提交于 2020-01-21 07:10:57

问题


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


回答1:


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.

E.g.

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;}



回答2:


This works:

#include <iostream>

struct Base {
virtual void print () const = 0;
protected:
int val;
};

struct Derived : Base {
void print () { std::cout << "Bases's val: " << val << std::endl; }
};


来源:https://stackoverflow.com/questions/1813671/problem-with-protected-fields-in-base-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!