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;
    }
    

      

  • 相关阅读:
    昨天又学到了dp
    LeetCode面试题17.13
    leetcode971
    今天又一题,单调队列leetcode862
    今天学到了一招,LeetCode863
    今天一道简单题,数组排序LeetCode973
    es面试题
    es的常用配置
    es基础一张图
    JMeter中引入外部的JAR包给bean shell 使用
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11972809.html
Copyright © 2011-2022 走看看