操作符重载

来源:互联网 发布:java考勤管理系统源码 编辑:程序博客网 时间:2024/04/28 10:20
操作符重载本质也就是函数调用而已!

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;//实部 
    int b;//虚部 
};

/*

Complex add(Complex c1,Complex c2)
{
    Complex c;
    c.a=c1.a+c2.a;
    c.b=c1.b+c2.b;
    return c;

*/
Complex operator+(Complex c1,Complex c2)
{
    Complex c;
    c.a=c1.a+c2.a;
    c.b=c1.b+c2.b;
    return c;

int main(int argc, char *argv[])
{
    Complex c1{1,2};

    Complex c2{1,2};

   //Complex c=operator+(c1,c2);

    Complex c=c1+c2;

    cout<<"c.a = "<<c.a<<endl;
    cout<<"c.b = "<<c.b<<endl;

    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

类的操作符重载
#include <cstdlib>
#include <iostream>

using namespace std;



class Complex
{
private:
    int a;
    int b;
public:
    Complex(int a=0,int b=0)
    {
        this->a=a;
        this->b=b;
    }

    friend Complex operator+(const Complex& c1,const Complex& c2);
    friend ostream& operator<<(ostream& out,const Complex& c);
};

//重载“+ ” 
Complex operator+(const Complex& c1,const Complex& c2)
{
    Complex c;
    c.a=c1.a+c2.a;
    c.b=c1.b+c2.b;
    return c;

//重载 "<<"
ostream& operator<<(ostream& out,const Complex& c)
{
    out<<c.a<<"+"<<c.b<<"i"; 
    return out;

int main(int argc, char *argv[])
{
    Complex c1(1,2);

    Complex c2(3,4);

    Complex c=c1+c2; //operator+(c1,c2)

    cout<<c<<endl;

    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

友元
可以访问private成员

成员函数重载只是需要右值作为操作数即可,因为默认左值是this指针

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
private:
    int a;
    int b;
public:
    Complex(int a=0,int b=0)
    {
        this->a=a;
        this->b=b;
    }

    Complex operator+(const Complex& c);

    friend ostream& operator<<(ostream& out,const Complex& c);
};

//重载“+ ” 
Complex Complex::operator+(const Complex& c2)
{
    Complex c;
    c.a=a+c2.a;
    c.b=b+c2.b;
    return c;

//重载 "<<"
ostream& operator<<(ostream& out,const Complex& c)
{
    out<<c.a<<"+"<<c.b<<"i"; 
    return out;

int main(int argc, char *argv[])
{
    Complex c1(1,2);

    Complex c2(3,4);

    Complex c=c1+c2; //--》  Complex c=c1.operator+(c2);

    cout<<c<<endl;

    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

成员函数重载操作符比全局操作符重载少一个参数
当无法修改左操作数时只能使用全局函数进行重载
=,[],()和->操作符只能通过成员函数进行重载

0 0
原创粉丝点击