C ++中的explicit关键字是什么意思? [英] What does the explicit keyword in C++ mean?

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

问题描述

有人在对C ++中的显式关键字的含义的另一个问题发表评论。

解决方案

在C ++中,编译器允许进行一个隐式转换来将参数解析为功能。这意味着编译器可以使用可通过单个参数调用的构造函数将一种类型转换为另一种类型,以便为参数获取正确的类型。



下面是一个可以用于隐式转换的构造函数示例类:

  class Foo 
{
public:
//单参数构造函数,可以用作隐式转换
Foo(int foo):m_foo(foo)
{
}

int GetFoo(){return m_foo; }

private:
int m_foo;
};

这里有一个简单的函数需要 Foo object:

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

这里是 DoBar
{
DoBar(42); c>




$ b}

参数不是 Foo object,但是 int 。但是,存在一个 Foo 的构造函数,它接受一个 int ,因此这个构造函数可以用来将参数转换为正确类型。



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



前缀 explicit 关键字阻止编译器使用该构造函数进行隐式转换。将它添加到上面的类将在函数调用 DoBar(42)时创建一个编译器错误。现在需要使用 DoBar(Foo(42))



明确调用转换。这样做是为了避免意外的建设,可以隐藏bug。创建示例:




  • 您有一个 MyString(int size)构造给定大小的字符串。你有一个函数 print(const MyString&),你用 print(3)调用它。您希望它打印3,但它打印的长度为3的空字符串。


Someone posted in a comment to another question about the meaning of the explicit keyword in C++. So, what does it 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;
};

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

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

and here's where the DoBar function is called.

int main ()
{
  DoBar (42);
}

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.

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:

  • 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 it with print(3). You expect it to print "3", but it prints an empty string of length 3 instead.

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

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