旧行李 2008-09-23 13:58 采纳率: 25%
浏览 359
已采纳

明确的关键词意味着什么?

What does the explicit keyword mean in C++?

转载于:https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean

  • 写回答

8条回答 默认 最新

  • ~Onlooker 2013-04-28 16:58
    关注

    The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

    Here's an example class with a constructor that can be used for implicit conversions:

    class Foo
    {
    public:
      // single parameter constructor, can be used as an implicit conversion
      Foo (int foo) : m_foo (foo) 
      {
      }
    
      int GetFoo () { return m_foo; }
    
    private:
      int m_foo;
    };
    

    Here's a simple function that takes a Foo object:

    void DoBar (Foo foo)
    {
      int i = foo.GetFoo ();
    }
    

    and here's where the DoBar function is called.

    int main ()
    {
      DoBar (42);
    }
    

    The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type.

    The compiler is allowed to do this once for each parameter.

    Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42). It is now necessary to call for conversion explicitly with DoBar (Foo (42))

    The reason you might want to do this is to avoid accidental construction that can hide bugs. Contrived example:

    • You have a MyString(int size) class with a constructor that constructs a string of the given size. You have a function print(const MyString&), and you call print(3) (when you actually intended to call print("3")). You expect it to print "3", but it prints an empty string of length 3 instead.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)