显式关键字是什么意思? [英] What does the explicit keyword mean?

查看:111
本文介绍了显式关键字是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

explicit 关键字在C ++中是什么意思?

What does the explicit keyword mean in C++?

推荐答案

允许编译器进行一次隐式转换,以将参数解析为函数。这意味着编译器可以使用可通过单个参数调用的构造函数从一种类型转换为另一种类型,以获得正确的参数类型。

The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

以下是带有可用于隐式转换的构造函数的示例类:

Here's an example class with a constructor that can be used for implicit conversions:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};

这是一个简单的函数,需要 Foo 对象:

Here's a simple function that takes a Foo object:

void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}

这是 DoBar

and here's where the DoBar function is called.

int main ()
{
  DoBar (42);
}

该参数不是 Foo 对象,但 int 。但是,存在 Foo 的构造函数,该构造函数采用 int ,因此可以使用该构造函数将参数转换为正确的类型。

The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type.

允许编译器为每个参数执行一次。

The compiler is allowed to do this once for each parameter.

对<$ c进行前缀构造函数的$ c> explicit 关键字可防止编译器使用该构造函数进行隐式转换。将其添加到上述类中将在函数调用 DoBar(42)中创建编译器错误。现在必须使用 DoBar(Foo(42))

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42). It is now necessary to call for conversion explicitly with DoBar (Foo (42))

显式地进行转换这样做是为了避免可能隐藏错误的意外构造。人为的例子:

The reason you might want to do this is to avoid accidental construction that can hide bugs. Contrived example:


  • 您有一个带有构造函数的 MyString(int size)类构造给定大小的字符串。您有一个函数 print(const MyString&),然后调用 print(3)(当您实际上意在调用 print( 3))。您希望它打印出 3,但是它打印出一个长度为3的空字符串。

  • You have a MyString(int size) class with a constructor that constructs a string of the given size. You have a function print(const MyString&), and you call print(3) (when you actually intended to call print("3")). You expect it to print "3", but it prints an empty string of length 3 instead.

这篇关于显式关键字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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