如果之前有人问过这样的问题,我很抱歉,但无论我搜索多少,我都找不到(有类似的问题,但似乎没有一个对我有用)。
我正在编写一个模板类,一切正常,除非我尝试重载 operator+。我尝试为不同的参数重载 operator+ 两次,但编译器看不到其中一个定义并给出错误。这是代码:
Worker.h(我以前的作业之一,在这里实现了这个问题,因为它更容易看到):
#ifndef _WORKER_H
#define _WORKER_H
#include <string>
#include "Project.h"
using namespace std;
template <class T>
class Worker {
public:
Worker(const string &, Project &);
void Work(const int &);
const Worker & Worker::operator+(const int &); //Problem
const Worker & Worker::operator+(const string &); //Problem
string getName() const;
int getTime() const;
private:
string myName; //The name of the worker
Project & myProject;
int myTime; //Variable to keep track of how much the worker worked.
};
#include "Worker.cpp"
#endif
以及 Worker.cpp 的相关部分:
template <class T>
const Worker<T> & Worker<T>::operator+(const int & add)
{
cout << add;
return *this;
}
template <class T>
const Worker<T> & Worker<T>::operator+(const string & add)
{
cout << add;
return *this;
}
+
运算符现在没有做任何事情,问题是编译器只看到第一个声明的函数(在这种情况下,带有参数 int)。这些功能似乎也没有问题,因为如果我只尝试重载一次,它们都可以单独工作。我也可以在非模板类中使用它们(进行必要的更改)。
我认为这很简单,但是由于我是模板新手,所以我无法弄清楚问题所在。