zoukankan      html  css  js  c++  java
  • 一元运算符重载 前置和后置++ --(这种一般用成员函数来实现重载)

    #include <iostream>
    
    using namespace std;
    //实现一元运算符的前置重载
    class A
    {
    public:
    	friend A operator++(A &t1);
    public:
    	void setA(int a)
    	{
    		this->a=a;
    	}
    	void getA()
    	{
    		cout<<a<<endl;
    	}
    public:
    	A operator--()
    	{
    		this->a--;
    		return *this;
    	}
    private:
    	int a;
    	
    };
    
    A operator++(A &t1)//友元函数
    {
    	t1.a++;
    	return t1;
    }
    
    
    int main()
    {
    	A a1;
    	a1.setA(10);
    	a1.getA();
    
    	++a1;
    	a1.getA();
    
    	--a1;
    	a1.getA();
    	system("pause");
    	return 0;
    }
    

      这里注意类的成员函数的重载中的形参永远比友元函数的形参少一个!!!!!!!

    #include <iostream>
    
    using namespace std;
    //实现一元运算符的前置重载
    class A
    {
    public:
    	friend A operator++(A &t1);
    	//A operator++(A & t2,int)
    	friend A operator++(A &t2,int);
    public:
    	void setA(int a)
    	{
    		this->a=a;
    	}
    	void getA()
    	{
    		cout<<a<<endl;
    	}
    public:
    	A operator--()//前置--
    	{
    		this->a--;
    		return *this;
    	}
    	A operator--(int)//后置--
    	{
    		return * this;
    		this->a--;
    	}
    private:
    	int a;
    	
    };
    
    A operator++(A &t1)//前置++友元函数
    {
    	t1.a++;
    	return t1;
    }
    
    A operator++(A & t2,int)//后置++友元函数,先返回在改变,使用占位操作符
    {
    	return t2;
    	t2.a ++;
    }
    int main()
    {
    	A a1;
    	a1.setA(10);
    	a1.getA();
    
    	++a1;
    	a1.getA();
    
    	--a1;
    	a1.getA();
    
    	a1++;
    	a1.getA();
    
    	a1--;
    	a1.getA();
    	system("pause");
    	return 0;
    }
    

      前置的很特别哟

  • 相关阅读:
    Spring-data-jpa和mybatis的比较及两者的优缺点?
    http和https的区别
    Springboot中spring-data-jpa实现拦截器
    RabbitMQ客户端页面认识
    设计模式之策略模式
    设计模式之策略模式应用实例(Spring Boot 如何干掉 if else)
    设计模式之装饰器模式
    网页跳转小程序
    好帖子
    git 回滚操作
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6582078.html
Copyright © 2011-2022 走看看