无法将函数定义与模板化类中的现有定义匹配
Unable match function definition to an existing definition in templated class
之前问过这样的问题,我很抱歉,但无论我搜索多少,我都找不到(有类似的问题,但似乎都不适合我(。
我正在编写一个模板化类,除了尝试重载 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
不应修改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) { }
等等。
请注意,对于应该影响对象状态的运算符,例如 +=
、 *=
等,通常的方法是使用成员运算符并通过引用返回,因为在这些情况下这是完全有意义的。
这里有 2 件事,其中 1 件事是你的问题
成员函数的返回类型不受类是模板这一事实的影响,因此operator+
返回Worker
的声明和返回Worker<T>
的定义是不同的。在类定义中,它们应该是:
const Worker<T> & operator+(const int &); //Problem
const Worker<T> & operator+(const string &); //Problem
在上面的代码中也更改的另一件事是你不需要类声明中的范围(Worker::
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数