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,但是拷贝没有)。

  • 相关阅读:
    1130
    Oracle 数据库常用操作语句大全
    Oracle用sys登陆报:ORA-28009:connection as sys should be as sysdba
    导出数据报ORA-39002: 操作无效 ORA-39070: 无法打开日志文件。 ORA-39087: 目录名 DUMP_DIR 无效
    SGI STL源码stl_bvector.h分析
    SGI STL源码stl_vector.h分析
    CGI 萃取技术 __type_traits
    迭代器iterator和traits编程技法
    智能指针分析及auto_ptr源码
    C++深拷贝和浅拷贝细节理解
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965657.html
Copyright © 2011-2022 走看看