构造函数有两个功能:1.初始化 2.类型转换
这里主要解释类型转换,单个参数的构造函数被称为转换构造函数。
转换构造函数的作用:初始化和类型转换
类型转换的步骤:
1.调用转换构造函数,将=右边的数 转换成类类型(生成一个临时对象)
2.将临时对象赋值给t对象,调用的是=运算符
Test.h
- //Test.h
- # ifndef _TEST_H_
- # define _TEST_H_
- class Test
- {
- public:
- Test();
- Test(int num);
- ~Test();
- //explicit Test(int num);
- void Display();
- private:
- int num_;
- };
- # endif //_TEST_H_
Test.cpp
- //Test.cpp
- # include "Test.h"
- # include <iostream>
- using namespace std;
- void Test::Display()
- {
- cout << num_ << endl;
- }
- Test::Test()
- {
- num_ = 0;
- cout<<"Initializing Default" << endl;
- }
- Test::Test(int num)
- {
- num_ = num;
- cout<<"Initializing "<<num_ << endl;
- }
- Test::~Test()
- {
- cout << "Destory " << num_ << endl;
- }
main.cpp
- # include "Test.h"
- int main(void)
- {
- Test t(10); //普通构造函数
- t = 20; //要将20这个整数赋值给t对象
- //1.调用转换构造函数,将20这个整数转换成类类型(生成一个临时对象)
- //2.将临时对象赋值给t对象,调用的是=运算符
- //赋值完就会马上销毁临时对象
- Test t2;
- return 0;
- }
运行结果:
如果不想让单参数的构造函数进行隐式的进行类类型转换,可以在构造函数的前面加上:
explicit关键字