C++ 赋值运算符重载

返回上一级

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

我们写一个范例重载 Rect 中的赋值运算符 ( = ),每次拷贝的时候就把 x 轴 和 y 轴各加 1

/**
 * file: main.cpp
 * author: 简单教程(www.twle.cn)
 *
 * Copyright © 2015-2065 www.twle.cn. All rights reserved.
 */

#include <iostream>

class Rect
{

private:

    double x;
    double y;

    double width;
    double height;

public:

    Rect()
    {
        x = 0;
        y = 0;
        width = 0;
        height = 0;
    }


    Rect(double a, double b )
    {
        x = 0;
        y = 0;
        width = a;
        height = b;
    }


    Rect(double a, double b, double c ,double d ) {
        x = a;
        y = b;
        width = c;
        height = d;
    }


    void display() {
        std::cout << "x: " << x << " y: " << y;
        std::cout << " width: " << width;
        std::cout << " height: " << height;
    }

    void operator= (const Rect &r )
    {
        x = r.x + 1;
        y = r.y + 1;

        width = r.width;
        height = r.height;
    } 
};


int main()
{
    Rect r1(5,5,3,4), r2(10,10,6,8);

    std::cout << "r1: ";
    r1.display();
    std::cout << "\n";

    std::cout << "r2: ";
    r2.display();
    std::cout << "\n";

    r1 = r2;

    std::cout << "r1: ";
    r1.display();
    std::cout << "\n";

    return 0;
}

编译和运行以上范例,输出结果如下:

r1: x: 5 y: 5 width: 3 height: 4
r2: x: 10 y: 10 width: 6 height: 8
r1: x: 11 y: 11 width: 6 height: 8

返回上一级

C++ 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.