我目前在Ubuntu9.10-c++工作。我需要在方法中定义一个泛型对象。我必须在.h文件中定义该方法。我该怎么做呢?我做了以下工作:
file.h
class ana
{
//code
public:
template <class T> bool method (T &Data);
};file.cpp
//code
template <class T>
bool ana::method(T &Data)
{
//code
}我已经创建了.a文件。
在test.cpp中
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}在用g++ test.cpp -o test libfile.a编译之后,我有一个错误:undefined reference to bool....,为什么?还有其他方法来创建泛型对象吗?
发布于 2011-05-09 14:10:23
将函数定义与声明(在头文件本身中)放在一起肯定有帮助,也是选择的方法。但是,如果您想要分隔函数定义,请在.cpp文件的末尾有以下行。它被称为explicit instantiation.This,它将处理链接器错误。我尝试了一些代码,基于您给出的内容,这似乎是可行的:
档案h:
#ifndef __ANA_H__
#define __ANA_H__
template <class T>
class ana {
public:
bool method(T& data);
};
#endiffile.cpp:
#include <ana.h>
#include <iostream>
using namespace std;
template <typename T>
bool ana<T>::method(T& data) {
cout << "Data = " << data << endl;
if(data > 0) {
return true;
}
return false;
}
//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);
template
bool ana<double>::method(double& data)使用此方法的缺点之一是,对于您希望此函数支持的每一种数据类型,都必须包括这些行。因此,现在方法函数将只运行于int和double。您的代码的规范应该是这样的,除了上面的内容之外,永远不会为数据类型调用方法。HTH,
斯里拉姆
发布于 2011-05-09 13:41:58
通常的问题。看看:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13。
把所有东西都放进头文件。
file.hpp
class ana
{
//code
public:
template <class T> bool method (T &Data)
{
//code
}
};将其包含在您的main.cpp中,它应该可以很好地工作。
#include "file.hpp"
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}发布于 2011-05-09 13:42:45
file.cpp构建到二进制文件中。。
https://stackoverflow.com/questions/5937653
复制相似问题