为什么隐式转换在C ++中是有害的 [英] why implicit conversion is harmful in C++

查看:94
本文介绍了为什么隐式转换在C ++中是有害的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如

  Foo {

public:
explicit Foo(int i){}
}

问题是,在什么条件下,应禁止隐式转换?为什么隐式转换有害?

解决方案

使用 explicit



显式仅适用于构造函数(或许多其中第一个是唯一没有默认值的)。



您可能希望随时使用显式关键字,程序员可能会错误地构造一个对象,做一些事情,它不是真的做。



下面是一个例子:

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

// ...其他东西b
$ b int size;
};

使用以下代码,您可以执行此操作:

  int age = 29; 
// ...
//许多代码
// ...
//这里假装程序员忘记了x的类型和思想字符串
str s = x;

但是调用者可能意味着在MyString变量中存储3而不是3。以获得编译错误,因此用户可以首先调用itoa或其他某些转换函数。



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

  class MyString 
{
public:
explicit MyString(int size)
:size(size)
{
}
b $ b // ...其他东西

int size;
};

编译错误总是比错误更好,因为它们可以立即显示,

I understand that the keyword explicit can be used to prevent implicit conversion.

For example

Foo {

 public:
 explicit Foo(int i) {}
}

My question is, under what condition, implicit conversion should be prohibited? Why implicit conversion is harmful?

解决方案

Use explicit when you would prefer a compiling error.

explicit is only applicable when there is one parameter in your constructor (or many where the first is the only one without a default value).

You would want to use the explicit keyword anytime that the programmer may construct an object by mistake, thinking it may do something it is not actually doing.

Here's an example:

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

     //... other stuff

    int size;
};

With the following code you are allowed to do this:

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

But the caller probably meant to store "3" inside the MyString variable and not 3. It is better to get a compiling error so the user can call itoa or some other conversion function on the x variable first.

The new code that will produce a compiling error for the above code:

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

     //... other stuff

    int size;
};

Compiling errors are always better than bugs because they are immediately visible for you to correct.

这篇关于为什么隐式转换在C ++中是有害的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆