为什么'explicit'关键字允许隐式转换?

dpb*_*dpb 3 c++

class Test {

    private:
    int value;

    public:
    void display(void)
    {
        cout << "Value [" << value << "]" << endl;
    }
    explicit Test(int i)
    {
        value=i;
    }   
};

int main() {

    Test a(5);
    Test b(4.9);

    a.display();
    b.display();

    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

即使提到了显式,浮点值也会转换为int.

我期望(错误地)浮点数不会转换为整数而对象b不会被构造.

Dre*_*ann 7

explicit不会阻止构造函数参数的隐式转换.这意味着构造函数本身可以不使用作为一个隐式转换到类类型Test.

void func( Test );  // function declaration

func( 5 ); // Your "explicit" makes this call an error.
Run Code Online (Sandbox Code Playgroud)

要防止构造函数(或任何函数)的参数的隐式转换,您可以使用C++ 11 = delete语法.

  Test(int i)
  {
      value=i;
  }   

  template<typename T>
  Test(const T&) = delete;
  // ^ Aside from your int constructor and the implicitly-generated 
  // copy constructor, this will be a better match for any other type
Run Code Online (Sandbox Code Playgroud)

  • 如果你没有 C++11,你可以使用 `template&lt;typename T&gt; Test(const T&amp;) { T::error(); 获得类似的效果。}`。 (2认同)