類型學(xué)轉(zhuǎn)換成其他類型有兩種方式:
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供江寧網(wǎng)站建設(shè)、江寧做網(wǎng)站、江寧網(wǎng)站設(shè)計(jì)、江寧網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、江寧企業(yè)網(wǎng)站模板建站服務(wù),10余年江寧做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
一、用構(gòu)造函數(shù),將基本類型轉(zhuǎn)為構(gòu)造類型
1.用初始化的形式;
class X
{
public:
X(int n);
~X();
};
void f(X arg);
...
int main(){
X(3);
X=a;//a隱式調(diào)用構(gòu)造函數(shù)X(int n);
f(5);//把5調(diào)用構(gòu)造函數(shù)X(int n)轉(zhuǎn)為X arg.然后調(diào)用構(gòu)造函數(shù)。
return 0;
}
二、因?yàn)?strong>帶參數(shù)的構(gòu)造函數(shù)無法將類類型轉(zhuǎn)為基本類型,所以設(shè)置類型轉(zhuǎn)換函數(shù)
#include
using namespace std;
class rational
{
public:
rational();
rational(int n,int d=1);
rational(double x);//將double類型轉(zhuǎn)換成類類型。
operator double();//將類類型轉(zhuǎn)變?yōu)閐ouble類型,且注意其沒有返回值。
friend rational& operator+(const rational&, const rational&);
friend ostream & operator <<( ostream& os, const rational&);
//注意這里輸出類ostream前面不可以加const因?yàn)樵谳敵隽鹘?jīng)過os時(shí)會修改os
//且類型一定是引用類型因?yàn)楸仨氂胏out對象本身
~rational();
private:
int numerator;
int denominator;
};
int gcd(int a, int b);
rational::rational()
{
numerator = 0;
denominator = 0;
}
rational::rational(int n,int d){
int g;
if (d == 1){
numerator = n;
denominator = d;
}
else{
g = gcd(n, d);//求分子分母的最大公約數(shù)
numerator = n / g;//把分母化成最簡;
denominator = d / g;
}
}
rational::rational(double x){
int a, b, g;
a = int(x*1e5);//x乘10的5次方。把小數(shù)變成整數(shù)
b = int(1e5);
g = gcd(a, b);
numerator = a / g;
denominator = b / g;
}
rational::~rational()
{
}
rational::operator double(){//雖然沒有返回值依然要返回double類型的數(shù)。
return double(numerator) / double(denominator);
}
rational& operator +(const rational& a, const rational& b){
rational c;
int d = a.denominator*b.denominator;
int n = a.numerator*b.denominator + a.denominator*b.numerator;
int g = gcd(n, d);
c.denominator = d / g;//將分子分母化為最簡
c.numerator = n / g;
return c;//返回類型是引用還是類類型都可以。
}
ostream& operator <<(ostream& os, const rational& a){
os << a.numerator;
if (a.denominator != 1){
os << "/" << a.denominator;
}
return os;//這里返回os類型的引用目的是連續(xù)使用cout<<"ss"<<"sss";
}
int gcd(int n, int d){//求最大公約數(shù)的算法
if (d == 0) return n;
else{
return gcd(d, n%d);
}
}
int main(){
rational a(2, 4);
rational b = 0.3;
rational c = a + b;
cout << double(a) << "+" << double(b)<<"="< //將類類型對象a,b,c轉(zhuǎn)換成double類型。 cout << a << "+" << b << "=" << c << endl; double x = b; c = x + 1 + 0.6; cout << x << "+" << 1 << "+" << 0.6 << "=" << c << endl; cout << rational(x) << "+" << rational(1) << "+" << rational(0.6) << "=" << c << endl; system("pause"); }
文章標(biāo)題:類類型與其他類型的轉(zhuǎn)換
本文URL:http://weahome.cn/article/jojgic.html