首页 > 其他 > 详细

operator重载的使用

时间:2015-03-30 20:29:41      阅读:239      评论:0      收藏:0      [点我收藏+]

C++的大多数运算符都可以通过operator来实现重载。

 

简单的operator+

#include <iostream>
using namespace std;

class A
{
public:
    A(int x){i=x;}
    int i;
    A &operator+(A &p)
    {
        this->i+=p.i;
        return *this;
    }
};

void main()
{
    A a(10),b(20),c(0);
    c=a+b;
    cout<<c.i<<endl;
    system("pause");
}

 

简单的operator++

#include <iostream>
using namespace std;

class A
{
public:
    A(int x){i=x;}
    int i;
    A &operator++()
    {
        this->i++;
        return *this;
    }
};

void main()
{
    A a(10);
    a++;
    cout<<a.i<<endl;
    system("pause");
}

 

深层operator=

#include <iostream>
using namespace std;

class A
{
public:
    A(int x){i=new int;*i=x;}
    ~A(){delete i;i=0;}
    A(const A&p)
    {
        i=new int;
        *i=*(p.i);
    }
    int *i;
    A &operator=(A &p)
    {
        *i=*(p.i);
        return *this;
    }
    int pp(){return *i;}
};

void main()
{
    A a(10),b(0);
    a=b;
    cout<<a.pp()<<endl;
    system("pause");
}

 

operator重载的使用

原文:http://www.cnblogs.com/BlackCat86/p/4378963.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!