Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 拥有一个转换构造函数有什么意义_C++ - Fatal编程技术网

C++ 拥有一个转换构造函数有什么意义

C++ 拥有一个转换构造函数有什么意义,c++,C++,在阅读了有关转换构造函数的内容后,我得出结论,它只是一个只有一个参数的类构造函数。这解释了很多,但是我仍然对它的使用感到困惑。为什么要用它?。到目前为止,我所理解的是,与其声明一个这样的实例 someclass a(12); 我们可以这样做 someclass a = 12; 它也很有用(危险),因为它可以自动转换参数 void print(std::string const& str) { std::cout << str << "\n";

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

someclass a(12);
我们可以这样做

someclass a = 12;
它也很有用(危险),因为它可以自动转换参数

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

当您想要进行隐式转换时,它会变得非常有用。比如说

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
}

如果你有一个转换构造函数

SomeClass( int )
这意味着一个函数

void foo( SomeClass x );
可以通过一个电话来满足

foo( 12 );

这可能是你想要的,也可能不是。
explicit
关键字用于避免此类“意外”转换。

std::string s=“hello world”在类似字符串的情况下,使用转换构造函数更自然。一些特性的实现仅仅是为了使语法更好。或者
ComplexNumber c=5如果您有一个充当数字或值的类,它也很有用。例如,一个高精度数字类,可以从int转换。不仅可以编写
someclass a=12
,还可以(例如)将
12
传递给需要
someclass
@V-X有效点的函数,但谁会想到编写一个转换运算符/构造函数,将整数转换为硬件设备的抽象?没关系,我可能不想知道…有用吗?检查。潜在危险?仔细检查,是的。毫无疑问,这是危险的。但这只是一个例子。我个人不会这么做,就像C++的很多特性一样。Stroustrup说,回想一下,它是为专业人士设计的。如果您打算滥用某个功能,请使用GTFO,直到您学会正确使用它;)+1感谢提及
explicit
,作为克服隐式转换问题的一种方式。感谢简短介绍,并在没有
explicit
关键字的情况下获得含义,
std::vector names=3将编译:/
foo( 12 );