zoukankan      html  css  js  c++  java
  • 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指针作为默认参数传入该函数
        }

    会被报错。

  • 相关阅读:
    vue开发(一)安装
    Ubuntu18.04安装mysql
    使用.NET Framework开发IIS 7.0模块和处理程序拦截请求实现跳转
    Mysql 清空数据后,释放硬盘文件
    依赖注入
    ubuntu 上开发.netcore
    使用python获取微医数据
    Mysql查询某字段重复值并删除重复值
    使用pyinstaller 打包python程序
    堆(heap)和栈(stack)、内存泄漏(memory leak)和内存溢出
  • 原文地址:https://www.cnblogs.com/dongling/p/5731880.html
Copyright © 2011-2022 走看看