c++中的隐式转换

隐式转换是什么?通过以下例子说明隐式转换的含义,首先创建一个类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;
}

运行结果如下:

我们发现每一次进行隐式转换都调用了一次构造函数,并且每次只有最新的那次起了作用,因此我们知道隐式转换的底层原理应该是重新构造了一次对象,原来的值也会变为随机数

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值