gpt4 book ai didi

c++ - 为什么隐式转换在 C++ 中有害

转载 作者:IT老高 更新时间:2023-10-28 21:35:13 24 4
gpt4 key购买 nike

我知道关键字explicit 可以用来防止隐式转换。

例如

Foo {

public:
explicit Foo(int i) {}
}

我的问题是,在什么情况下应该禁止隐式转换?为什么隐式转换有害?

最佳答案

如果您希望出现编译错误,请使用 explicit

explicit 仅适用于构造函数中有一个参数(或许多第一个参数是唯一没有默认值的参数)的情况。

在程序员可能错误地构造对象的任何时候,您都希望使用 explicit 关键字,认为它可能会做一些实际上并没有做的事情。

这是一个例子:

class MyString
{
public:
MyString(int size)
: size(size)
{
}

//... other stuff

int size;
};

使用以下代码,您可以这样做:

int age = 29;
//...
//Lots of code
//...
//Pretend at this point the programmer forgot the type of x and thought string
str s = x;

但是调用者可能打算将“3”存储在 MyString 变量中,而不是 3。最好得到一个编译错误,以便用户可以先调用 itoa 或 x 变量上的一些其他转换函数。

对上述代码产生编译错误的新代码:

class MyString
{
public:
explicit MyString(int size)
: size(size)
{
}

//... other stuff

int size;
};

编译错误总是比错误好,因为它们立即可见,您可以更正。

关于c++ - 为什么隐式转换在 C++ 中有害,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2346083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com