ami*_*iad 5 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;
}
Run Code Online (Sandbox Code Playgroud)
此代码提供以下错误:
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; }
};
Run Code Online (Sandbox Code Playgroud)
我只是无法理解第一个代码的问题是什么...
每次我真的需要写"A ::"是没有意义的...
您还可以使用this->t访问基类模板成员.
在B::get(),名称t不依赖于模板参数T,因此它不是依赖名称.基类A<T>显然依赖于模板参数T,因此是依赖的基类.在从属基类中不查找非依赖名称. 可以在C++ FAQ Lite中找到为什么会出现这种情况的详细说明.
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |