C++入坑第一天:C++隐式类类型转换

2 篇文章 0 订阅

C++隐式类类型转换

《C++ Primer》中7.5.4提到:“能通过一个实参调用的构造函数定义了一条从构造函数的参数类型类类型隐式转换的规制。”

"能通过一个实参调用的构造函数"不是特指只有一个形参的构造函数,它可以有多个形参,但那些形参都是有默认值的。

#include <string>
#include <iostream>
using namespace std;

struct Sales_data
{
	string bookNo;
   	unsigned units_sold;
   	double revenue;
   	Sales_data() = default;
   	Sales_data(const string &s, unsigned n=1, double p=1.5f):bookNo(s), units_sold(n), revenue(p*n){}
   	string combin(const Sales_data &);
};
string Sales_data::combin(Sales_data &that)
{
	units_sold = that.units_sold;
	revenue = that.revenue;
	return that.bookNo;
}
int main()
{
    Sales_data A("A");
    Sales_data B("B");
    cout << A.combin(B) << endl;
    cout << A.combin(string("C")) << endl;
    cout << A.combin(Sales_data("D")) << endl;
    return 0;
}

A.combin(string(“C”)) 发生一个隐式转换:string类型到Sales_data类型,借助Sales_data的构造函数进行转换,以满足combin函数的参数期待。

隐式类类型转换还是会带来风险的,隐式转换得到类的临时变量,完成操作后就消失了,因此我们可以通过explicit声明来抑制这种隐式转换。

struct Sales_data
{
   	explicit Sales_data(const string &s, unsigned n=1, double p=1.5f):bookNo(s), units_sold(n), revenue(p*n){}
	// 其余的代码一样
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值