面向对象之构造函数和析构函数之五

来源:互联网 发布:黑桐谷嫂的淘宝店 编辑:程序博客网 时间:2024/04/28 01:45

题:请看下面一段程序:

// P110_example5.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <string>#include <vector>class B{private:int data;public:B(){std::cout<<"default constructor!"<<std::endl;}~B(){std::cout<<"destructed!"<<std::endl;}B(int i) : data(i){std::cout<<"constructed by parameter "<<data<<std::endl;}};B Play(B b){return b;}int _tmain(int argc, _TCHAR* argv[]){B temp = Play(5);return 0;}
问题:

(1)该程序输出的结果是什么?为什么会有这样的输出?

(2)B(int i):data(i),这种用法的专业术语叫什么?

(3)Play(5),形参类型是类,而5是个常量,这样写合法吗?为什么?【英国著名图形图像公司A2008年面试题】

答案:

(1)程序的输出结果为:

注:5首先转换成B类型,调用一个有参的构造函数,然后Play返回之后,局部变量b会被析构掉。整个程序返回后,temp会调用析构函数。

(2)带参数的构造函数,冒号后面是成员变量初始化列表(members initialization list)。

(3)合法。单个参数的构造函数如果不添加explicit关键字,会定义一个隐含的类型转换(从参数的类型转换到自己);添加explicit关键字会消除这种隐含转换