旧行李 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条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大