什么是转换构造函数的重点

时间:2013-05-17 18:15:50

标签: c++

在阅读了转换构造函数后,我得出结论,它只是一个具有一个参数的类构造函数。这个page解释了很多但是我仍然对它的使用感到困惑。为什么用它?到目前为止,我所理解的是,不是将实例声明为

someclass a(12);

我们可以像

那样做
someclass a = 12;

3 个答案:

答案 0 :(得分:6)

它也很有用(dangerious)因为它可以自动转换参数。

 void print(std::string const& str)
 {
     std::cout << str << "\n";
 }


 int main()
 {
     print("Hi"); // That's not a string.
                  // But the compiler spots that std::string has a single 
                  // argument constructor that it can use to convert a 
                  // `char const*` into a std::string with.
 }

基本上可以使语言更简单(read)。

有一个不幸的副作用(他们在事后发现)。编译器将转换您可能不想自动转换的内容。想不到一个人。但他们存在。因此,他们为构造函数添加了explicit关键字。这会阻止自动编译器转换(因为您需要显式调用它)。

感谢@Mooing Duck

int main()
{
     std::vector<int>  names = 3; // What does this mean?
                                  // This does not compile because of the explicit keyword now.
                                  // But it used to compile and the meaning is not obvious.

     // It gets even worse if you think about a function that takes a vector
     plop(3); // Do you want that to auto converted into an std::vector<int>?
              // Would you not want a compiler error?
}

答案 1 :(得分:5)

如果您有转换构造函数

SomeClass( int )

这意味着一个功能

void foo( SomeClass x );
通过

的召唤可以满足

foo( 12 );

这可能是也可能不是你想要的。 explicit关键字用于避免此类“令人惊讶的”转化。

答案 2 :(得分:3)

当您想要执行隐式转换时,此功能非常有用。例如

struct A {
    A(int i) : i(i) {}
    A() : A(0) {}
    int i;
    A operator+(const A& a) {
        return A(i + a.i);
    }
};

void f(A a) {}

int main() {
    A a(1);
    A c = a + 2;  // This wont be possible with out the implicit conversion of 2 to A
    f(3);         // This wont be possible with out the implicit conversion of 3 to A
}
相关问题