gpt4 book ai didi

C++:从模板参数继承

转载 作者:太空狗 更新时间:2023-10-29 20:03:48 25 4
gpt4 key购买 nike

在下一个代码示例中:

#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 已知之前)并且将它绑定(bind)到 ::f。如果你想让它调用成员函数 f,那么使用 this 使它成为依赖名称:

template<class T>
struct C : public T {
C() {
cout << this->f() << endl;
}
};

关于C++:从模板参数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com