類類型與其他類型的轉換

類型學轉換成其他類型有兩種方式:

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供江寧網站建設、江寧做網站、江寧網站設計、江寧網站制作等企業(yè)網站建設、網頁設計與制作、江寧企業(yè)網站模板建站服務,10余年江寧做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。

    一、用構造函數,將基本類型轉為構造類型

        1.用初始化的形式;

            

class X

{

public:

X(int n);

~X();

};

void f(X arg);

...

int main(){

    X(3);

    X=a;//a隱式調用構造函數X(int n);

    f(5);//把5調用構造函數X(int n)轉為X arg.然后調用構造函數。

    return 0;

}

    二、因為帶參數的構造函數無法將類類型轉為基本類型,所以設置類型轉換函數

#include<iostream>

using namespace std;

class rational

{

public:

rational();

rational(int n,int d=1);

rational(double x);//將double類型轉換成類類型。

operator double();//將類類型轉變?yōu)閐ouble類型,且注意其沒有返回值。

friend rational& operator+(const rational&, const rational&);

friend ostream & operator <<( ostream& os, const rational&);

//注意這里輸出類ostream前面不可以加const因為在輸出流經過os時會修改os

        //且類型一定是引用類型因為必須用cout對象本身

~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);//求分子分母的最大公約數

numerator = n / g;//把分母化成最簡;

denominator = d / g;

}

}

rational::rational(double x){

int a, b, g;

a = int(x*1e5);//x乘10的5次方。把小數變成整數

b = int(1e5);

g = gcd(a, b);

numerator = a / g;

denominator = b / g;

}

rational::~rational()

{

}

rational::operator double(){//雖然沒有返回值依然要返回double類型的數。

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){//求最大公約數的算法

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;

//將類類型對象a,b,c轉換成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");

}

本文標題:類類型與其他類型的轉換
瀏覽路徑:http://muchs.cn/article2/jojgic.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供Google、小程序開發(fā)、網站建設動態(tài)網站、面包屑導航、微信小程序

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網站建設