Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c++ - 显式关键字是什么意思?(What does the explicit keyword mean?)

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

  ask by Skizz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(这是一个带有Foo对象的简单函数:)

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

and here's where the DoBar function is called.

(这就是DoBar函数的调用位置。)

int main ()
{
  DoBar (42);
}

The argument is not a Foo object, but an int .

(该参数不是Foo对象,而是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.

(但是, Foo有一个采用int构造函数,因此可以使用该构造函数将参数转换为正确的类型。)

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.

(在explicit关键字前面加上构造函数,可以防止编译器将该构造函数用于隐式转换。)

Adding it to the above class will create a compiler error at the function call DoBar (42) .

(将其添加到上述类中将在函数调用DoBar (42)创建编译器错误。)

It is now necessary to call for conversion explicitly with DoBar (Foo (42))

(现在必须使用DoBar (Foo (42))明确调用转换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.

    (您有一个MyString(int size)类,该类的构造函数构造了给定大小的字符串。)

    You have a function print(const MyString&) , and you call print(3) (when you actually intended to call print("3") ).

    (您有一个函数print(const MyString&) ,并且您调用了print(3) (当您实际上打算调用print("3") )。)

    You expect it to print "3", but it prints an empty string of length 3 instead.

    (您希望它打印“ 3”,但是它将打印一个长度为3的空字符串。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...