explicit构造函数的作用

xiaoxiao2021-02-28  95

      explicit构造函数是用来防止隐式转换的。看下面一段代码: class Test1 { public: Test1(int n){num = n ;}; //普通构造函数 private: int num ; }; class Test2 { public: explicit Test2(int n ){num = n ;} //explicit(显示)构造函数 private: int num ; }; int main() { Test1 t1 = 12 ; //隐式调用其构造函数,成功 Test2 t2 = 12 ; //编译错误,不能隐式调用其构造函数 Test2 t3(12) ; //显示调用成功 return 0 ; }

      Test1的构造函数带一个int型参数,代码第19行会隐式转换成调用Test1的这个构造函数。而Test2的构造函数被声明为explicit(显示),这表示不能通过隐式转换来调用这个构造函数,因此代码第20行会出现编译错误。

      普通构造函数能被隐式调用,而explicit构造函数只能被显示调用。

      下面的程序f()被调用时,输出是什么:

#include <iostream> #include <string> using namespace std ; class Number { public: string type ; Number() : type("void") {} explicit Number(short) : type("short") {} Number(int) :type("int"){} }; void Show(const Number& n){cout<<n.type ;} void main() { short s = 42 ; Show(s) ; }      Show函数的参数类型是Nunmber类对象的引用,代码第19行调用Show(s)时采取了以下的步骤:

(1)Show(s)中的s为short类型,其值为42,因此首先检查参数为short的构造函数能否被隐式转换。由于代码第10行的构造函数被声明为显示调用(explicit),因此不能隐式转换。于是进行下一步。

(2)42自动转换为int类型。

(3)检查参数为int的构造函数能否被隐式转换。由于代码第11行参数为int的构造函数没有被声明为显示调用,因此调用此构造函数构造出一个临时对象。

(4)打印上一步临时对象的type成员,即“int”

      所以最后输出的结果为:int

转载请注明原文地址: https://www.6miu.com/read-42297.html

最新回复(0)