实践如下:

#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++,这样学起来应该会更好一点。

posted on 2019-07-17 09:16  大辉_FFf  阅读(347)  评论(0编辑  收藏  举报