重载操作符必须接受零或一个参数
Overloaded operator must take zero or one argument
是的,以前有人问过这个问题,但问题是操作符是一个成员函数,而这里不是这样。这些是我的文件:
minmax.h
#ifndef MINMAX_H
#define MINMAX_H
class MinMax
{
private:
int m_nMin;
int m_nMax;
public:
MinMax(int nMin, int nMax);
int GetMin() { return m_nMin; }
int GetMax() { return m_nMax; }
friend MinMax operator+(const MinMax &cM1, const MinMax &cM2);
friend MinMax operator+(const MinMax &cM, int nValue);
friend MinMax operator+(int nValue, const MinMax &cM);
};
#endif // MINMAX_H
minmax.cpp
#include "minmax.h"
MinMax::MinMax(int nMin, int nMax)
{
m_nMin = nMin;
m_nMax = nMax;
}
MinMax MinMax::operator+(const MinMax &cM1, const MinMax &cM2)
{
//compare member variables to find minimum and maximum values between all 4
int nMin = cM1.m_nMin < cM2.m_nMin ? cM1.m_nMin : cM2.m_nMin;
int nMax = cM1.m_nMax > cM2.m_nMax ? cM1.m_nMax : cM2.m_nMax;
//return a new MinMax object with above values
return MinMax(nMin, nMax);
}
MinMax MinMax::operator+(const MinMax &cM, int nValue)
{
//compare member variables with integer value
//to see if integer value is less or greater than any of them
int nMin = cM.m_nMin < nValue ? cM.m_nMin : nValue;
int nMax = cM.m_nMax > nValue ? cM.m_nMax : nValue;
return MinMax(nMin, nMax);
}
MinMax MinMax::operator+(int nValue, const MinMax %cM)
{
//switch argument places and pass them to previous operator version
//this avoids duplicate code by reusing function
return (cM + nValue);
}
main.cpp
#include <iostream>
#include "minmax.h"
using namespace std;
int main()
{
MinMax cM1(10, 15);
MinMax cM2(8, 11);
MinMax cM3(3, 12);
//sum all MinMax objects to find min and max values between all of them
MinMax cMFinal = cM1 + 5 + 8 + cM2 + cM3 + 16;
cout << cMFinal.GetMin() << ", " << cMFinal.GetMax() << endl;
return 0;
}
消息为error: 'MinMax MinMax::operator+(const MinMax&, const MinMax&)' must take either zero or one argument
把我的评论变成一个答案:
你把你的函数定义为一个成员函数,把MinMax::
放在它的前面,所以它们是成员函数。
MinMax MinMax::operator+(const MinMax &cM, int nValue)
{ // should be operator+ without the MinMax:: at the front.
//compare member variables with integer value
//to see if integer value is less or greater than any of them
int nMin = cM.m_nMin < nValue ? cM.m_nMin : nValue;
int nMax = cM.m_nMax > nValue ? cM.m_nMax : nValue;
return MinMax(nMin, nMax);
}
你可以看到它在这里起作用
正如你所说,它们不是成员函数。
因此,在它们的定义中,MinMax::
前缀是不正确的,不应该在那里。
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何制作一个将函数作为参数的类方法
- 修改函数中的指针(将另一个指针作为参数传递)
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 构造函数在退出函数时无法初始化一个参数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 运算符重载:"operator+"必须采用零个或一个参数
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 如何在另一个函数中使用返回值作为参数?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 将参数一个接一个地传递,或通过将它们包裹在数组,结构或元组中
- 如何给一个参数一个由其他参数的函数确定的默认值
- C++如何给一个参数一个特定的枚举,它可以是
- 如果我在默认构造函数中放了一个参数,但给了这个参数一个默认值,它还是一个默认构造函数吗
- 为什么在c++中给typename模板参数一个默认值0 ?