zoukankan      html  css  js  c++  java
  • C++ class 外的 ++ 重载,左++,右++,重载示例。

    #include <iostream>
    
    // overloading "operator ++ " outside class
    // ++ 是一元操作符
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    	Rectangle(int w, int h) 
    		: width(w), height(h)
    	{};
    
    	~Rectangle() {};
    
    public:
    	int width;
    	int height;
    };
    
    
    //////////////////////////////////////////////////////////
    
    
    
    //////////////////////////////////////////////////////////
    
    std::ostream&
    operator<< (std::ostream& os, const Rectangle& rec)
    {
    	os << rec.width << ", " << rec.height;
    	return  os;
    
    }
    
    
    Rectangle &
    operator++ (Rectangle& ths)
    {
    	ths.height++;
    	ths.width++;
    	return  ths;
    }
    
    Rectangle
    operator++ (Rectangle& ths, int)
    {
    	Rectangle b(ths);
    	++(ths);
    	return  b;
    }
    
    //////////////////////////////////////////////////////////
    
    int main()
    {
    	Rectangle a(40, 10);
    	Rectangle b = (a++);
    	std::cout
    		<< "a = " << a << std::endl		// 输出 41, 11
    		<< "b = " << b << std::endl		// 输出 40, 10
    		;
    	Rectangle c = (++a);
    
    	std::cout
    		<< "a = " << a << std::endl		// 输出 42, 12
    		<< "b = " << b << std::endl		// 输出 40, 10
    		<< "c = " << c << std::endl		// 输出 42, 12
    		;
    
    	std::cout
    		<< "a = " << a << std::endl		// 输出 43, 13
    		<< "a = " << ++a << std::endl	// 输出 43, 13
    		;
    
    	std::cout
    		<< "a = " << (a++) << std::endl	// 输出 43, 13
    		;
    
    	// C++ 自带的 ++ 作用结果
    
    	{
    		int vint = 0;
    		std::cout
    			<< "v = " << vint << std::endl;		// 输出 0
    		std::cout
    			<< "v = " << vint << std::endl		// 输出 1
    			<< "v = " << vint++ << std::endl;	// 输出 1
    	}
    
    	{
    		int vint = 0;
    		std::cout
    			<< "v = " << vint << std::endl;		// 输出 0
    		std::cout
    			<< "v = " << vint << std::endl		// 输出 1
    			<< "v = " << ++vint << std::endl;	// 输出 1
    	}
    
    	return 0;
    }
    

      

    ++i,应该是先自加一,返回自身(已经加1之后的自身);

    i++,应该是先拷贝自身,再自加一,返回自身的拷贝(自己已经加1,但是拷贝没有)。

  • 相关阅读:
    [C#] 等待启动的进程执行完毕
    C# 、winform 添加皮肤后(IrisSkin2) label设置的颜色 无法显示
    Mysql 备份
    Mysql 慢查询日志配置
    Mysql 忘记密码处理配置
    PHP-FPM 慢执行日志、网站隔离配置
    PHP-FPM 设置多pool、配置文件重写
    Nginx 代理配置
    Nginx 301与302配置
    Nginx URL跳转
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965657.html
Copyright © 2011-2022 走看看