淺談C++類型轉(zhuǎn)化(運算符重載函數(shù))和基本運算符重載(自增自減)
類型轉(zhuǎn)化(運算符重載函數(shù))
用轉(zhuǎn)換構造函數(shù)可以將一個指定類型的數(shù)據(jù)轉(zhuǎn)換為類的對象。但是不能反過來將一個類的對象轉(zhuǎn)換為一個其他類型的數(shù)據(jù)(例如將一個Complex類對象轉(zhuǎn)換成double類型數(shù)據(jù))。在C++提供類型轉(zhuǎn)換函數(shù)(type conversion function)來解決這個問題。類型轉(zhuǎn)換函數(shù)的作用是將一個類的對象轉(zhuǎn)換成另一類型的數(shù)據(jù)。
類型轉(zhuǎn)換函數(shù)的一般形式為:
operator 類型名( ){
實現(xiàn)轉(zhuǎn)換的語句
}
下面是簡單實現(xiàn)。這時候,Base起了兩方面的作用:類和數(shù)據(jù)類型。系統(tǒng)會在需要的時候自動調(diào)用對應的類方法。
#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;
}
基本運算符重載(自增自減)
主要總結 自增自減的前置和后置的用法。其他的加減乘除較簡單。
簡單的代碼實現(xiàn)(純語法)
#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ū)別是有無int參數(shù)。
后置需要申請新的空間,大小是類的大小。所以,后置操作會有額外的時間空間開銷。
盡量使用前置操作:如:for (int i=0;i<n;++i)
以上這篇淺談C++類型轉(zhuǎn)化(運算符重載函數(shù))和基本運算符重載(自增自減)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C++11新特性之右值引用與完美轉(zhuǎn)發(fā)詳解
C++11標準為C++引入右值引用語法的同時,還解決了一個短板,即使用簡單的方式即可在函數(shù)模板中實現(xiàn)參數(shù)的完美轉(zhuǎn)發(fā)。本文就來講講二者的應用,需要的可以參考一下2022-09-09
編譯錯誤error: stray ‘\343’in program的解決方法
以下是對編譯錯誤error: stray ‘\343’in program的解決方法進行了詳細的分析介紹,如遇此問題的朋友們可以過來參考下2013-07-07

