gpt4 book ai didi

c++ - 返回子类型的成员模板函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:28 24 4
gpt4 key购买 nike

是否有正确的方法为模板类定义成员函数,返回子类的实例?

这是一个无法在 VC++ 2010 中编译的示例:

template<class T> class A {
public:
class B {
public:
T i;
};

A();
B* foo();
};

/////////////////////////////////////////////

template<class T> A<T>::A() {}

template<class T> A<T>::B* A<T>::foo() {
cout << "foo" << endl;
return new B();
}

我明白了

Error   8   error C1903: unable to recover from previous error(s); stopping compilation 

foo定义开始的行。

我对 iostream 等有正确的包含和命名空间声明。

谢谢大家!

编辑:

根据要求,这是完整的错误列表,全部在同一行:

Warning 1   warning C4346: 'A<T>::B' : dependent name is not a type
Error 2 error C2143: syntax error : missing ';' before '*'
Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 4 error C1903: unable to recover from previous error(s); stopping compilation
Warning 5 warning C4346: 'A<T>::B' : dependent name is not a type
Error 6 error C2143: syntax error : missing ';' before '*'
Error 7 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 8 error C1903: unable to recover from previous error(s); stopping compilation

最佳答案

姓名A<T>::B是相关的,您需要提示编译器相关名称是类型

template<class T> typename A<T>::B* A<T>::foo() {...}

此行相同:return new B(); -> return new typename A<T>::B();

阅读:Where and why do I have to put the "template" and "typename" keywords?

关于c++ - 返回子类型的成员模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414610/

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