随笔 - 173  文章 - 1  评论 - 26  阅读 - 43万

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

会被报错。

 

posted on   HorseShoe2016  阅读(15113)  评论(2编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示