隐式转换是什么?通过以下例子说明隐式转换的含义,首先创建一个类cat
#include <iostream>
#include <string>
using namespace std;
class cat
{
public:
cat(string _name,int _age,double _weight)
{
name=_name;
age=_age;
weight=_weight;
}
cat(string _name)
{
name=_name;
cout<<"仅带一个参数name的构造函数"<<endl;
}
cat(int _age)
{
age=_age;
cout<<"仅带一个参数age的构造函数"<<endl;
}
cat(double _weight)
{
weight=_weight;
cout<<"仅带一个参数weight的构造函数"<<endl;
}
private:
int age;
double weight;
string name;
};
int main()
{
string newname="wangcai";
cat cat1=newname;
cat cat2=18;
cat cat3=12.3;
}
运行结果如下:
在主函数我们通过直接赋值的方式初始化了三个对象,但是按理说cat1,cat2,cat3是cat类型,而初始化的值依次是string,int,double类型,为什么能够成功赋值呢,这就是c++11的隐式转换规则——当存在参数仅有一个的构造函数时,允许直接将值赋值给对象完成初始化。
同时,隐式转换有很多有意思的现象,即在隐式转换的过程中,总是调用构造函数(而不是视为一次赋值),并且当对一个对象进行多次隐式转换,仅有最后一次隐式转换生效。
#include <iostream>
#include <string>
using namespace std;
class cat
{
public:
cat(string _name,int _age,double _weight)
{
name=_name;
age=_age;
weight=_weight;
}
cat(string _name)
{
name=_name;
cout<<"仅带一个参数name:"<<_name<<"的构造函数"<<endl;
}
cat(int _age)
{
age=_age;
cout<<"仅带一个参数age:"<<_age<<"的构造函数"<<endl;
}
cat(double _weight)
{
weight=_weight;
cout<<"仅带一个参数weight:"<<_weight<<"的构造函数"<<endl;
}
void display()
{
cout<<"姓名:"<<this->name+" "<<"年龄:"<<this->age<<" "<<"体重:"<<this->weight<<endl;
}
private:
int age;
double weight;
string name;
};
int main()
{
string newname="wangcai";
cat cat1=newname;
cat1.display();
cat1=18;
cat1.display();
cat1=19.2;
cat1.display();
cat1=14;
cat1.display();
return 0;
}
运行结果如下:
我们发现每一次进行隐式转换都调用了一次构造函数,并且每次只有最新的那次起了作用,因此我们知道隐式转换的底层原理应该是重新构造了一次对象,原来的值也会变为随机数