我对C ++还是很陌生,但是知道大多数其他主流编程语言。我一直在网上寻找解决问题的方法,但似乎找不到。到目前为止,这是我的一些代码:
object.h:
class Object final {
public:
template <Component T>
const Component& AddComponent<T>();
};
object.cpp:
#include "object.h"
template <Component T>
const Component& Object::AddComponent<T>() {
}
问题在于在模板关键字之后的行上未解析符号“ T”。我在Linux上使用eclipse和g ++编译器。
答案 0 :(得分:0)
首先,在c ++中,final关键字表示子类不会重载虚拟类方法,这与您的使用方式无关。因此,该关键字应消失。
然后,“组件”在c ++中不存在。您使用它的方式使我觉得它是一个类型名,因为您正在返回的是“ Component”类型的元素。您应该首先定义它,或者,如果它应该是因函数的不同调用而有所不同的类型名,则应将其作为模板参数。
您也不应该在函数的声明中写“
最后但并非最不重要的一点是,函数模板的定义应在头文件中指定,因为实例化是必需的。
因此,正确的语法应为:
object.h:
class Object {
public:
template <typename Component, Component T>
const Component &AddComponent() {
// adding component and return statement here.
}
};
示例main.cpp:
#include "object.h"
int main() {
Object obj;
obj.AddComponent<int, 4>();
return 0;
}
object.h(如果预定义了“组件”):
class Object {
public:
template <Component T>
const Component &AddComponent() {
// adding component and return statement here.
}
};
main.cpp(如果预定义了“组件”):
#include "object.h"
int main() {
Object obj;
obj.AddComponent<4>();
return 0;
}
今天过得愉快。
PS:对不起,如果我犯了任何英语错误,我是法语。