zoukankan      html  css  js  c++  java
  • C++ explicit关键字,修饰构造函数,ctor

    #include <iostream>
    
    // operator Type() 类型操作符重载
    // operator int()
    // operator double()
    // ...
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    #ifdef Want_compiler_to_add__function_of_int_2_Rectangle
    	Rectangle(const int w, const int h = 1)
    		: width(w), height(h)
    	{};
    #else
    	explicit Rectangle(const int w, const int h = 1)
    		: width(w), height(h)
    	{};
    #endif // Want_compiler_to_add__function_of_int_2_Rectangle
    
    	~Rectangle() {};
    	operator int(); // 重载 int() 之后,Rectangle就可以像一个int被使用。
    
    public:
    	int width;
    	int height;
    };
    
    
    //////////////////////////////////////////////////////////
    
    Rectangle::operator int()
    {
    	return width * height;
    }
    
    
    //////////////////////////////////////////////////////////
    
    void 
    printInt(const int v)
    {
    	std::cout << v+5 << std::endl;
    }
    
    int
    main()
    {
    	Rectangle b = 10;	// 这可以通过的原因是,调用了Rectangle的构造函数。编译器自动为int添加了转化为 Rectangle 的方法。但是有时候这不是我们想要的行为。
    						// 显式的为构造函数添加 explicit 就可以杜绝这种编译器的自动行为。
    						// 添加之后,该行就会报错。
    	return 0;
    }
    

      

  • 相关阅读:
    .net core2.2
    9_山寨系统调用 SystemCallEntry
    7_API调用
    8_InlineHook
    6_再次开中断STI的正确姿势
    5_中断现场下
    4_中断现场中
    3_中断现场上
    2_多核复杂性
    1_中断提权
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11972809.html
Copyright © 2011-2022 走看看