前言
记录看书复习到的2个知识点
- 委托构造函数
- 类类型自动转换
c++11标准之后,类允许初始化数据成员,但是根据抽象派(老派)人员的观点,类一个抽象的东西,怎么能有具体的数值呢,就算要有默认数据成员,也可以通过委托构造函数完成啊。
类类型自动转换,就是成员函数的参数如果是类的时候,而构造函数中的有通过其他类类型构造的,会由编译器自动进行类型转换
代码演示
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class TestA
{
private:
	std::string _name;
public:
	TestA(const std::string& name) :_name(name) {}
	TestA() :TestA("") {} // 委托构造函数
	
	TestA& add(const TestA& rgh) { _name += rgh._name; return *this; }
	std::string& getName() { return _name; }
};
int main()
{
	TestA a("a");
	a.add(string("b")); // 类型自动转换: string -> TestA
	cout << a.getName() << endl;
	return 0;
}
结果:
 
 但是如果我将TestA(const std::string& name)声明为显示调用的话,自动转换就会报错。
 



















