我试图了解为什么我在这段代码上遇到错误: (错误在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/