如果以前有人问过这样的问题,我很抱歉,但无论我搜索多少,我都找不到(有类似的问题,但似乎没有一个对我有用)。
我正在编写一个模板化类并且一切正常,除非我尝试重载 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)。这些功能似乎也没有问题,因为如果我只尝试重载一次,它们都可以单独工作。我也可以在非模板类中使用它们(进行必要的更改)。
我认为这很简单,但由于我是模板的新手,所以我无法弄清楚问题出在哪里。
最佳答案
您的方法存在一些与模板无关的问题。
首先您的运算符只适用于一种操作顺序:Worker<T> + int
, 而不是 int + Worker<T>
其次 通常您会希望返回一个新的 Worker 实例,而不是返回 this
作为引用,因为 A+B
不应修改 A
或 B
.
所以你可以做的是为不同的顺序定义非成员运算符:
template <typename T>
Worker<T> operator+(int i, const Worker<T>& t) { }
template <typename T>
Worker<T> operator+(const Worker<T>& t, int i) { }
等等。
请注意,对于应该影响对象状态的运算符,例如+=
, *=
等等,通常的方法是使用成员运算符并通过引用返回,因为在这些情况下它非常有意义。
关于c++ - 无法将函数定义与模板化类中的现有定义相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10372302/