C++ 类型转换运算符

发表于:2015-7-20 10:48

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:陆小果1008    来源:51Testing软件测试网采编

#include <iostream>
using namespace std;
class SmallInt
{
public:
/**
* implicit constructor
* 实现int类型转换为SamllInt类型
*/
SmallInt(const int val): value(val)
{
cout << "SmallInt(const int val)" << endl;
}
/**
* class-type conversion
* 无显式返回类型
* 无形参
* 必须定义成类的成员函数
* 一般被定义成const类型
*/
operator int()const /* SmallInt类型在需要的时候会转化为int类型 */
{
cout << "operator int()const" << endl;
return value;
}
int getValue() const
{
return value;
}
private:
int value;
};
void testTypeConversion()
{
SmallInt smallInt = 1;/* SmallInt smallInt = SmallInt(1) */
cout << smallInt.getValue() << endl;
cout << smallInt + 2 << endl;
}
void testTypeConversion2nd()
{
SmallInt smallInt = 3.14;/* 3.14转化为int型为3 */
cout << smallInt.getValue() << endl;
cout << smallInt + 3.14 << endl; /* SmallInt类型先转化为int,再转化为double*/
}
int main()
{
testTypeConversion();
testTypeConversion2nd();
return 0;
}
  运行结果如下图所示:
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号