Problem with protected fields in base class in c++

后端 未结 2 1944
情深已故
情深已故 2021-01-12 23:03

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 DerivedCla

相关标签:
2条回答
  • 2021-01-12 23:24

    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;}
    
    0 讨论(0)
  • 2021-01-12 23:36

    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; }
    };
    
    0 讨论(0)
提交回复
热议问题