類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))

10年積累的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先做網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有英吉沙免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
用轉(zhuǎn)換構(gòu)造函數(shù)可以將一個(gè)指定類型的數(shù)據(jù)轉(zhuǎn)換為類的對(duì)象。但是不能反過(guò)來(lái)將一個(gè)類的對(duì)象轉(zhuǎn)換為一個(gè)其他類型的數(shù)據(jù)(例如將一個(gè)Complex類對(duì)象轉(zhuǎn)換成double類型數(shù)據(jù))。在C++提供類型轉(zhuǎn)換函數(shù)(type conversion function)來(lái)解決這個(gè)問(wèn)題。類型轉(zhuǎn)換函數(shù)的作用是將一個(gè)類的對(duì)象轉(zhuǎn)換成另一類型的數(shù)據(jù)。
類型轉(zhuǎn)換函數(shù)的一般形式為:
operator 類型名( ){
實(shí)現(xiàn)轉(zhuǎn)換的語(yǔ)句
}下面是簡(jiǎn)單實(shí)現(xiàn)。這時(shí)候,Base起了兩方面的作用:類和數(shù)據(jù)類型。系統(tǒng)會(huì)在需要的時(shí)候自動(dòng)調(diào)用對(duì)應(yīng)的類方法。
#include <iostream>
using namespace std;
class Base{
private:
float x;
int y;
public:
Base (float xx=0,int yy=0){
x = xx;
y = yy;
}
operator float (){
return x;
}
operator int (){
return y;
}
void display(){
cout<<"x is :"<<x<<";y is :"<<y<<endl;
}
};
int main()
{
Base base(1.0,2);
base.display();
int y= base;
float x= base;
cout<<"NewX is :"<<x<<"NewY is:"<<y<<endl;
return 0;
}基本運(yùn)算符重載(自增自減)
主要總結(jié) 自增自減的前置和后置的用法。其他的加減乘除較簡(jiǎn)單。
簡(jiǎn)單的代碼實(shí)現(xiàn)(純語(yǔ)法)
#include <iostream>
using namespace std;
class Base{
private:
float x;
int y;
public:
Base (float xx=0,int yy=0){
x = xx;
y = yy;
}
operator float (){
return x;
}
operator int (){
return y;
}
Base operator ++(){//前置 ++
x++;
y++;
return *this;
}
Base operator --(){
x--;
y--;
return *this;
}
Base operator ++(int ){//后置 ++
Base temp = *this;
++(*this);
return temp;
}
Base operator --(int ){
Base temp = *this;
--(*this);
return temp;
}
void display(){
cout<<"x is :"<<x<<";y is :"<<y<<endl;
}
};
int main()
{
Base base(1.0,1);
Base tem = base++;
base.display();
tem.display();
Base base2(1.0,1);
tem = ++base2;
base.display();
tem.display();
return 0;
}發(fā)現(xiàn):
后置和前置的區(qū)別是有無(wú)int參數(shù)。
后置需要申請(qǐng)新的空間,大小是類的大小。所以,后置操作會(huì)有額外的時(shí)間空間開(kāi)銷。
盡量使用前置操作:如:for (int i=0;i<n;++i)
以上這篇淺談C++類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))和基本運(yùn)算符重載(自增自減)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持創(chuàng)新互聯(lián)。
網(wǎng)站標(biāo)題:淺談C++類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))和基本運(yùn)算符重載(自增自減)
網(wǎng)站地址:http://chinadenli.net/article8/jgjoop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、自適應(yīng)網(wǎng)站、域名注冊(cè)、品牌網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、軟件開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)