zoukankan      html  css  js  c++  java
  • 运算符重载

    运算符重载

    成员函数单目

    #include<iostream>
    using namespace std;
    class A{
    	int p;
    public:
    	A (int a){
    		p = a;
    	}
    	A operator++(){
            p++;
            return *this;
    	}
    	A operator++(int){
    		A temp(*this);
    		p++;
    		return temp;
    	}
    	void show(){
    		cout<<p<<endl;
    	}
    };
    int main(int argc, char const *argv[])
    {
    	A a(10);
    	++a;
    	a++;
    	a.show();
    	return 0;
    }
    

    成员函数双目

    #include<cstring>
    #include<iostream>
    using namespace std;
    class A{
    	int p;
    public:
    	A (int a){
    		p = a;
    	}
    	A operator +(A& a);/*这里的&一定要用*/
    	void show(){
    		cout<<p<<endl;
    	}
    };
    A A:: operator +(A& a){/*不用友元时,相当于用了一波this,强调一下他直接第一个调用*this*/
    		A temp(0);/*这里不能用 A temp*/
    		temp.p = p + a.p;
    		return temp;
    }
    int main(int argc, char const *argv[])
    {
    	A a(10),b(5);
    	A c = a + b;
        c.show();
    	return 0;
    }
    

    友元函数单目

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<iostream>
    using namespace std;
    class A{
    	int p;
    public:
    	A(int a){
            p = a;
    	};
    	friend A operator ++(A &a){
           a.p++;
           return a;
    	}
    	friend A operator++(A &a,int){
    		A temp = a;
    		a.p++;
    		return temp;
    	}
        void show(){
    		cout<<p<<endl;
    	}
    };
    int main(int argc, char const *argv[])
    {
    	A a(10);
        a++;
        a.show();
    	return 0;
    }
    

    友元函数双目

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<iostream>
    using namespace std;
    class A{
    	int p;
    public:
    	A(int a){
            p = a;
    	};
    	friend A operator +(A &a,A &b){
           A c(0);
           c.p = a.p + b.p;
           return c;
    	}
        void show(){
    		cout<<p<<endl;
    	}
    };
    int main(int argc, char const *argv[])
    {
    	A a(10),b(10);
    	A c = a + b; 
        c.show();
    	return 0;
    }
    
  • 相关阅读:
    文件比较运算符
    中山慧海人才市场9月份 现场招聘会预告
    80后智能科技公司诚聘业务人员
    元豪路灯厂诚聘
    对Discuz的简单认识
    discuz阅读权限的设置作用
    个人对织梦系统的认识
    awvs的用法
    cain使用方法
    CCNA笔记(1)
  • 原文地址:https://www.cnblogs.com/ARTlover/p/14147833.html
Copyright © 2011-2022 走看看