1.??operator 用于類型轉換函數:
類型轉換函數的特征:
1)??型轉換函數定義在源類中;
2)??須由 operator 修飾,函數名稱是目標類型名或目標類名;
3)??函數沒有參數,沒有返回值,但是有return
語句,在return語句中返回目標類型數據或調用目標類的構造函數。
類型轉換函數主要有兩類:
1)??對象向基本數據類型轉換:
? ? 對象向不同類的對象的轉換:
例程1:
//通過類型轉換函數求半徑為5的圓的面積
//并將其存儲在float型變量中打印輸出
#i nclude <iostream>
using namespace std;
class CArea
{
???????float area;
public:
???????CArea()
???????{
??????????????area=0;
???????}
???????CArea(float a)???????????//重載含有一個參數的構造函數
???????{
??????????????area=a;
???????}
???????void getArea()
???????{
??????????????cout<<area<<endl;
???????}
???????void setArea(float a)
???????{
??????????????area=a;
???????}
???????operator float()????????????//類型轉換函數
???????{??????????????????????????????
//將面積類對象轉換為float型數據
??????????????return area;
???????}
};
class CCircle
{
???????float R;
public:
???????void getR()
???????{
??????????????cout<<R<<endl;
???????}
???????void setR(float r)
???????{
??????????????R=r;
???????}
???????operator CArea()???//類型轉換函數
???????{?????????????????????????????????//將圓類對象轉為面積類對象
??????????????float area=3.1415926*R*R;
??????????????return (CArea(area));
???????}???
};
void main()
{
???????CCircle cir;
???????CArea are;
???????float a;
???????cir.setR(5);
???????cir.getR();?????????????????????//打印圓的半徑
???????are.getArea();???????????//打印轉換前的面積??????????????????
????
???????are=cir;?????????????????//將圓類對象轉為面積類對象
???????are.getArea();???????????//打印轉換后的面積???
???????a=are;??????????????????????????//將面積類對象轉換為float型數據
???????cout<<a<<endl;???????????????????
}
2.??operator 用于操作符重載:
操作符重載的概念:
????
??將現有操作符與一個成員函數相關聯,并將該操作符與其成員對象(操作數)一起使用。
注意事項:
1)??重載不能改變操作符的基本功能,以及該操作符的優先級順序。
2)??重載不應改變操作符的本來含義。
3)??只能對已有的操作符進行重載,而不能重載新符號。
4)??操作符重載只對類可用。
5)??以下運算符不能被重載:
.???????原點操作符(成員訪問符)
*?????指向成員的指針
::???????作用域解析符
? :?????問號條件運算符
sizeof 操作數的字節數
???操作符函數的一般格式:
???????????????return_type operator op(argument list);
??????return_type:返回類型(要得到什么)
????????op:要重載的操作符
??????argument list:參數列表(操作數有哪些)
例程2:
//重載大于號操作符比較兩個人的工資
#i nclude <iostream>
using namespace std;
class employee
{
???????int salary;
public:
???????void setSalary(int s)
???????{
??????????????salary=s;
???????}
???????void getSalary()
???????{
??????????????cout<<salary<<endl;
???????}
???????bool operator >(const employee & e)//重載大于號操作符
???????{
??????????????if(salary > e.salary)
?????????????????????return true;
??????????????else
?????????????????????return false;
???????}
};
void main()
{
???????employee emp1,emp2;
???????emp1.setSalary(1000);
???????emp2.setSalary(2000);
???????if (emp1 > emp2)
???????{
??????????????cout<<"emp1比emp2工資高"<<endl;
???????}
???????else
???????{
??????????????cout<<"emlp1沒有emp2工資高"<<endl;
???????}
}
轉自:http://blog.sina.com.cn/s/blog_6ac4a2d3010127cl.html