dongling

  在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指针作为默认参数传入该函数
    }

会被报错。

 

分类:

技术点:

相关文章:

  • 2021-06-25
  • 2021-04-23
  • 2021-12-09
  • 2021-10-08
  • 2021-09-16
  • 2021-06-06
  • 2021-08-11
  • 2022-01-05
猜你喜欢
  • 2021-10-26
  • 2021-11-03
  • 2020-04-12
  • 2021-11-20
  • 2021-07-27
  • 2021-11-03
  • 2020-05-30
相关资源
相似解决方案