溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

類類型與其他類型的轉(zhuǎn)換

發(fā)布時(shí)間:2020-07-02 16:05:44 來(lái)源:網(wǎng)絡(luò) 閱讀:270 作者:神跡難覓 欄目:編程語(yǔ)言

類型學(xué)轉(zhuǎn)換成其他類型有兩種方式:

    一、用構(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)?span >帶參數(shù)的構(gòu)造函數(shù)無(wú)法將類類型轉(zhuǎn)為基本類型,所以設(shè)置類型轉(zhuǎn)換函數(shù)

#include<iostream>

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í)會(huì)修改os

        //且類型一定是引用類型因?yàn)楸仨氂胏out對(duì)象本身

~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;//把分母化成最簡(jiǎn)

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;//將分子分母化為最簡(jiǎn)

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)<<"="<<double(c)<<endl;

//將類類型對(duì)象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");

}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI