Template overlay problem

I am trying to understand that I am getting an error message in this code: (the error is under the g ++ unix compiler, VS compiles OK)

template<class T> class A {
public:
    T t;
public:
    A(const T& t1) : t(t1) {}
    virtual void Print() const { cout<<*this<<endl;}
    friend ostream& operator<<(ostream& out, const A<T>& a) {
            out<<"I'm "<<typeid(a).name()<<endl;
            out<<"I hold "<<typeid(a.t).name()<<endl;
            out<<"The inner value is: "<<a.t<<endl;
            return out;
    }
};

template<class T> class B : public A<T> {
public:
    B(const T& t1) : A<T>(t1) {}
    const T& get() const { return t; }
};

int main() {
    A<int> a(9);
    a.Print();
    B<A<int> > b(a); 
    b.Print();
    (b.get()).Print();  
    return 0;
}

This code gives the following error:

main.cpp: In the member function 'const T & B :: get () const':
main.cpp: 23: error: 't' was not declared in this area

It compiled when I changed the B code to this:

template<class T> class B : public A<T> {
public:
    B(const T& t1) : A<T>(t1) {}
    const T& get() const { return A<T>::t; }
};

I just can’t understand what the problem is with the first code ...
It makes no sense that I really need to write "A ::" every time ...

+5
source share
1 answer

You can also use this->tto access a member of a base class template.

B::get() t t, . A<T>, , t , , . . , , ++ FAQ Lite.

+7

All Articles