c++ - 模板继承的问题

标签 c++ inheritance templates

我试图了解为什么我在这段代码上遇到错误: (错误在g++ unix编译器下,VS编译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;
}

此代码给出以下错误:

main.cpp: 在成员函数'const T& B::get() const'中:
main.cpp:23: 错误:“t”未在此范围内声明

当我将 B 的代码更改为这样时,它确实编译了:

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

我只是不明白第一个代码有什么问题...
我真的每次都需要写“A::”是没有意义的......

最佳答案

您还可以使用 this->t访问基类模板成员。

B::get() , 名字 t不依赖于模板参数 T ,所以它不是从属名称。基类A<T>显然依赖于模板参数 T因此是一个依赖基类。不在依赖基类中查找非依赖名称。 A detailed description of why this is the case can be found in the C++ FAQ Lite .

关于c++ - 模板继承的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2982660/

相关文章:

c++ - 模板化类内部函数的模板特化

c++ - 将 uint16_t * 数组转换为 std::vector

未调用 C++ 重写函数

c++ - 如何在实例和静态范围之间创建成员变量?

c++ - 如何制作一系列函数,将不同类的参数 vector 作为参数?

c++ - 从基类对象创建派生类

templates - 如何覆盖 MATLAB 中的默认文本

c++ - 使用 Eigen header 的模板函数

c++ - 缓存了多少缓存行?

c++ - 使用 getline 从 for 循环中的流中安全读取