加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++ 操作符重载实践 & java没有重载操作符的思路

发布时间:2020-12-16 07:19:04 所属栏目:百科 来源:网络整理
导读:实践如下: #include iostream using namespace std; class Book{ private : int page; public : Book( int no){ cout " 构造器: " no endl; page = no; } virtual ~ Book(){} int getPage(){ return page; } // + 符合重载运算 Book operator + (Book b){

实践如下:

#include <iostream>
using namespace std;

class Book{

    private:
        int page;

    public:
        Book(int no){
            cout<<"构造器:"<<no<<endl;
            page = no;
        }
        virtual ~Book(){}
        int getPage(){
            return page;
        }
        // + 符合重载运算
        Book operator+(Book b){
            // 这个方式是返回当前对象
            this->page += b.page;
            return *this;
            // 这个方式返回一个新对象
            //return Book(page + b.page);
        }

        Book operator+(int no){
            this->page += no;
            return *this;
        }
        Book operator+=(int no){
            this->page += no;
            return *this;
        }
        // int 代表后置
        Book operator++(int){
            this->page ++;
            return *this;
        }
        // 无int 代表前置
        Book operator++(){
            ++page;
            return *this;
        }

        Book operator=(int no){
            page = no;
            return *this;
        }

        // 重载转换运算符
        operator double(){
            return page;
        }

};

int main(){

    cout << "重载操作符实践:" << endl;

    // 调用无参构造器
    Book bk1(100);
    Book bk2(200);
    //Book bk3(0);
    Book bk3 = bk1 + bk2;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    bk3 = bk3 + 100;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    bk3 += 100;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    bk3 ++;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    ++ bk3;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    bk3 = 666;
    cout << "bk3.getPage(): " << bk3.getPage() << endl;

    cout << "(double)bk3: " << (double)bk3 << endl;

    cout << "重载操作符实践 end." << endl;

    return 0;
}

java中为什么不支持重载运算符:

https://zhidao.baidu.com/question/395158734721133165.html

确实吧,java是一门高级的 简易的 语言。

感觉大学教学的时候,应该先教java 再教C/C++,这样学起来应该会更好一点。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读