所以,我遇到了链接问题。答案可能很简单,但我想我是傻了。我定义了一个类来计算需要字符串流的东西。
头文件的相关部分:
#include <sstream>
using namespace std;
template<class T>
class Finder {
public:
Finder(istringstream& input) {};
~Finder() {};
template<typename T> Finder(T& input) {};
template<typename T> ~Finder() {};
T check(istringstream&);
template<typename T> friend ostream& operator << (ostream&, Finder<t>&);
};
template<class T>
T Finder<T>::check(istringstream& input)
然后我的驱动文件到最后一次调用:
#include <sstream>
#include <string>
#include <iostream>
#include "Finder.h"
using namespace std;
int main(int argc, char** argv) {
Finder<int> thing;
string expression;
getline(cin, expression);
while(expression[0] != 'q') {
try {
int result = thing.check(istringstream(expression));
错误是: 1>driver.obj : error LNK2019: 未解析的外部符号 "public: __thiscall Finder::Finder(void)"(??0?$Finder@H@@QAE@XZ) 在函数 _main 中引用
1>driver.obj:错误 LNK2019:未解析的外部符号“public:__thiscall Finder::~Finder(void)”(??1?$Finder@H@@QAE@XZ) 在函数 __catch$_main$0 中引用
最佳答案
首先,不要将您的输入限制为仅字符串流。请改用通用 std::istream
,除非您有充分的理由不这样做。您的类将更加健壮并且能够从多个源流类型获取输入,而不仅仅是 std::istringstream
(例如文件流或输入控制台)。
其次,我几乎可以肯定这就是您尝试要做的:
#include <iostream>
// forward declare class
template<class T>
class Finder;
// forward declare ostream inserter
template<class T>
std::ostream& operator <<(std::ostream&, const Finder<T>&);
// full class decl
template<class T>
class Finder
{
// friend only the inserter that matches this type, as opposed to
// all inserters matching all T for Finder
friend std::ostream& operator<< <>(std::ostream&, const Finder<T>&)
{
// TODO: implement inserter code here
}
public:
Finder()
{
// TODO: default initialization here
};
Finder(const T& value)
{
// TODO: initialize directly from T value here.
}
Finder(std::istream& input)
{
// TODO: initialize from input stream here.
}
~Finder()
{
// TODO: either implement this or remove it outright. so far
// there is no evidence it is even needed.
}
T check(std::istream& input)
{
// TODO: implement check code here. currently just returning a
// value-initialized T. you will change it as-needed
return T();
};
};
示例用法是:
int main()
{
Finder<int> f;
std::istringstream iss("1 2 3");
f.check(iss);
}
注意有一个 T
,它来自类模板本身。如果需要成员函数(甚至构造函数)的辅助类型,也可以使用具有不同类型名称的模板成员函数,例如:
template<class T>
class Simple
{
public:
// a template member constructor
template<typename U>
Simple(const U& val)
{
}
// a regular template member
template<typename U>
void func(U value)
{
}
};
并像这样调用:
Simple<int> simple(3.1415926); // U will be type double
simple.func("test"); // U will be type const (&char)[5]
注意成员函数模板,就像所有函数模板一样,类型是从传递的参数中推导的,而不是指定的(尽管它们可能是强制特定类型,我们在这里不这样做) .
无论如何,希望对您有所帮助。
关于c++ - LNK2019带模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439205/