是的,之前已经问过这个问题,但问题是运营商是会员功能,而且这不是问题。这些是我的文件:
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
答案 0 :(得分:5)
将我的评论转变为答案:
您通过将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);
}
你可以看到它正常工作here
答案 1 :(得分:2)
正如您所说,他们不是会员职能。
因此,在他们的定义中,MinMax::
前缀不正确,不应该在那里。