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

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值