C++笔记(1)----此运算符函数的参数太多

  在VS2015中定义了这样一个类:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Integer {
public :
    int num = 0;
    Integer(int num) {
        this->num = num;
    }
    Integer() {
        Integer(0);
    }
    bool operator< (const Integer& lh, const Integer& rh) {
        return rh.num < lh.num;
    }
};

  对于重载的 < 运算符,显示如下错误:

  网上查找原因,解释如下:

1.你为Book类定义operator==作为成员函数,所以它有一个隐式的Book*参数this指针
2. 一个双目运算符重载应该在类定义之外。 class Book { ... }; bool operator==(const Book& a, const Book & b) { return a.Return_ISBN()==b.Return_ISBN(); }

重新如下定义就对了:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Integer {
public :
    int num = 0;
    Integer(int num) {
        this->num = num;
    }
    Integer() {
        Integer(0);
    }
    
};
//双目运算符重载定义在类外
bool operator< (const Integer& lh, const Integer& rh) {
    return rh.num < lh.num;
}

如果必须要在类内定义的话,只能定义为单参数的运算符函数:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Integer {
public :
    int num = 0;
    Integer(int num) {
        this->num = num;
    }
    Integer() {
        Integer(0);
    }
    bool operator< (const Integer& rh) {
        return rh.num < this->num;    //this指针作为默认参数传入该函数
    }
    
};

此时,如果在源文件中定义了如下的模板函数:

template<typename T>
int compare(const T& a,const T& b)
{
    if (a < b)
        return -1;
    if (b < a)
        return 1;
    return 0;
}

则该模板函数只接受类外定义的双目运算符:

bool operator< (const Integer& lh, const Integer& rh) {
    return rh.num < lh.num;
}

而类内定义的单参数运算符

bool operator< (const Integer& rh) {
        return rh.num < this->num;    //this指针作为默认参数传入该函数
    }

会被报错。

原文地址:https://www.cnblogs.com/dongling/p/5731880.html