无法将函数定义与模板化类中的现有定义匹配

Unable match function definition to an existing definition in templated class

本文关键字:定义 函数      更新时间:2023-10-16
如果

之前问过这样的问题,我很抱歉,但无论我搜索多少,我都找不到(有类似的问题,但似乎都不适合我(。

我正在编写一个模板化类,除了尝试重载 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

以及工人的相关部分.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;
}

+运算符现在没有做任何事情,问题是编译器只看到第一个声明的函数(在本例中为 with 参数 int(。这些功能似乎也没有问题,因为如果我只尝试重载一次,它们都可以单独工作。我也可以在非模板化类中使用它们(进行必要的更改(。

我认为这很简单,但由于我是模板的新手,我无法弄清楚问题是什么。

您的方法存在一些问题,与模板无关。

首先,您的运算符只适用于一种操作顺序:Worker<T> + int而不是int + Worker<T>

其次,通常您希望返回一个新的 Worker 实例,而不是通过引用返回this,因为A+B不应修改AB

因此,您可以做的是为不同的排序定义非成员运算符:

template <typename T>
Worker<T> operator+(int i, const Worker<T>& t) { }
template <typename T>
Worker<T> operator+(const Worker<T>& t, int i) { }

等等。

请注意,对于应该影响对象状态的运算符,例如 +=*= 等,通常的方法是使用成员运算符并通过引用返回,因为在这些情况下这是完全有意义的。

这里有 2 件事,其中 1 件事是你的问题

成员函数的返回类型不受类是模板这一事实的影响,因此operator+返回Worker的声明和返回Worker<T>的定义是不同的。在类定义中,它们应该是:

const Worker<T> & operator+(const int &); //Problem
const Worker<T> & operator+(const string &); //Problem

在上面的代码中也更改的另一件事是你不需要类声明中的范围(Worker::