?? 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 + -