赋值运算符重载

99封情书 提交于 2019-11-26 20:22:43

重载赋值运算符(=),用于创建一个对象,比如拷贝构造函数。

/***
evaluate.cpp
***/
#include<iostream>
using namespace std;

class Distance
{
    private:
        int feet;
        int inches;
    public:
        Distance()
        {
            feet = 0;
            inches = 0;
        }
        Distance(int f,int i)
        {
            feet = f;
            inches = i;
        }

        void displayDistance()
        {
            cout << "F: " << feet << " I: " << inches << endl; 
        }

        Distance operator=(const Distance &D)
        {
            feet = D.feet;
            inches = D.inches;
        }
};

int main()
{
    Distance D1(11,10), D2(5,11);

    cout << "First Distance : ";
    D1.displayDistance();
    cout << "Second Distance : ";
    D2.displayDistance();

    D1 = D2;
    cout << "First Distance : ";
    D1.displayDistance();
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190809$ g++ evaluate.cpp -o evaluate

exbot@ubuntu:~/wangqinghe/C++/20190809$ ./evaluate

First Distance : F: 11 I: 10

Second Distance : F: 5 I: 11

First Distance : F: 5 I: 11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!