码迷,mamicode.com
首页 > 其他好文 > 详细

二元运算符重载

时间:2019-08-08 18:56:24      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:nbsp   运算符重载   display   调用   wan   space   ble   names   namespace   

以非成员函数方式重载运算符

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

class Box
{
    public:
        Box(double l = 2.0,double b = 2.0,double h = 2.0)
        {
            length = l;
            breadth = b;
            height = h;
        }
        double getVolume()
        {
            return length*breadth*height;
        }
    private:
        double length;
        double breadth;
        double height;
    friend Box operator+(const Box& a,const Box& b);
};

Box operator+(const Box& a,const Box& b)
{
    Box box;
    box.length = a.length+b.length;
    box.breadth = a.breadth+b.breadth;
    box.height = a.height + b.height;
    return box;
}

int main()
{
    Box box1(3.3,1.2,1.5);
    Box box2(8.5,6.0,2.0);
    Box box3;
    double volume = 0.0;

    volume = box1.getVolume();
    cout << "Volume of box1 : " << volume << endl;

    volume = box2.getVolume();
    cout << "Volume of box2 : " << volume << endl;

    box3 = box1 + box2;

    volume = box3.getVolume();
    cout << "Volume of box3 : " << volume << endl;

    return 0;
}

运算结果:

exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ overtwo.cpp -o overtwo

exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overtwo

Volume of box1 : 5.94

Volume of box2 : 102

Volume of box3 : 297.36

 

当两个对象相加时是没有顺序要求的,但是要重载+让其与一个数字相加有顺序要求,可以通过加一个友元函数使另一个顺序的输出合法。

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

class A
{
    private:
        int a;
    public:
        A();
        A(int n);
        A operator+(const A &obj);
        A operator+(const int b);
    friend A operator+(const int b,A obj);
        void display();
};

A::A()
{
    a = 0;
}

A::A(int n)
{
    a = n;
}

A A::operator +(const A& obj)  //重载+号,用于对象相加
{
    return this->a+obj.a;
}

A A::operator+(const int b) //对象和数相加
{
    return A(a+b);
}

A operator+ (const int b, A obj) // 友元函数调用第二个重载+的成员函数,相当于obj.operator(b)
{
    return obj+b;
}

void A::display()
{
    cout << a << endl;
}

int main()
{
    A a1(1);
    A a2(2);
    A a3,a4,a5;
    a1.display();
    a2.display();
    int m = 1;
    a3 = a1 + a2; //可以调换顺序,相当于a3=a1.operator+(a2);
    a3.display();

    a4 = a1 + m; //加了一个友元函数可调换顺序
    a4.display();

    a5 = m + a1;
    a5.display();

    return 0;
}

运算结果:

exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overfrined

1

2

3

2

2

二元运算符重载

标签:nbsp   运算符重载   display   调用   wan   space   ble   names   namespace   

原文地址:https://www.cnblogs.com/wanghao-boke/p/11319659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!