我是靠谱客的博主 轻松舞蹈,最近开发中收集的这篇文章主要介绍构造函数 explicit 关键字的作用, from stackoverflow,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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 parameter 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.

转载于:https://www.cnblogs.com/lthxk-yl/p/5149561.html

最后

以上就是轻松舞蹈为你收集整理的构造函数 explicit 关键字的作用, from stackoverflow的全部内容,希望文章能够帮你解决构造函数 explicit 关键字的作用, from stackoverflow所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(31)

评论列表共有 0 条评论

立即
投稿
返回
顶部