重载操作符必须接受零或一个参数

Overloaded operator must take zero or one argument

本文关键字:参数 一个 操作符 重载      更新时间:2023-10-16

是的,以前有人问过这个问题,但问题是操作符是一个成员函数,而这里不是这样。这些是我的文件:

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::前缀是不正确的,不应该在那里。

相关文章: