📄 ep4_9.cpp
字号:
/* 4.9 内置数据类型可以进行类型强制转换,类也可以进行同样的转换,这是通过定义
类型转换函数实现的,它只能是类的成员函数,不能是友元函数。格式为:
类名::operator 转换后的数据类型( ) {…}
如:operator float()是转换为浮点数的成员函数。使用时的格式为:
float(对象名); 或 (float) 对象名;
定义人民币类,数据成员包括:圆、角、分,均为整型。类型转换函数将人民币类强制转
换为浮点数,以圆为单位。并编程进行检验。
*/
#include<iostream>
using namespace std;
class IntRMB{ //人民币类
private:
int IYuan;
int Jiao;
int Fen;
public:
IntRMB(int y=0,int j=0,int f=0); //构造函数
void print(); //数据输出函数
operator float(); //浮点数类型转换函数
};
IntRMB::IntRMB(int y,int j,int f){//构造函数
IYuan=y;
Jiao=j;
Fen=f;
}
IntRMB::operator float(){
float temp;
temp=float(IYuan + (Jiao/10.0) + (Fen/100.0));
return temp;
}
void IntRMB::print(){
cout <<IYuan << "元" <<Jiao << "角" <<Fen <<"分" <<endl;
}
int main(){
float a;
IntRMB Im(10,25,3);
cout << "***转换前***" <<endl;
Im.print();
a=float(Im); //使用重载的类型关键字进行强制类型转换
cout << "***转换后***" <<endl;
cout<<a<<"圆"<<endl;
a=(float)Im; //使用重载的类型关键字进行强制类型转换
cout << "***转换后***" <<endl;
cout<<a<<"圆"<<endl;
getchar(); //按任意键结束运行
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -