在下一个代码示例中:
#include <iostream>
using namespace std;
int f() {
return 0;
}
struct A {
int f() {
return 1; }
};
template<class T>
struct C : public T {
C() {
cout << f() << endl;
} };
int main() {
C<A> c; // prints 0
return 0;
}
如果我将继承更改为非模板,如下所示: struct C : public A
然后它会显示“ 1”而不是0。
这是为什么?
在f()
,f
是一个非依赖的名字,所以名字查找发生在模板定义时间(之前T
是已知的),并结合它::f
。如果希望它调用成员函数f,则使用this
它作为从属名称:
template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句