- 重載操作符能使得一個自定義類型可以像基本類型一樣支持加減乘除等多種操作
引例
引入struct/class可以允許用戶自己定義數(shù)據(jù)類型,但是自定義類型相比基本類型還是有些不足。
自定義類型不能進行加減乘除
//用fraction表示分數(shù)
class Fraction
{
public:
Fraction():num(1),den(2)
{
}
Fraction(int n,int d):num(n),den(d)
{
}
int num;//分子
int den;//分母
};
Fraction fa(2,3);//表示2/3
Fraction fb; //表示1/2
//Fraction fc = fa+fb; 錯誤!相加沒有意義
算數(shù)操作符
包括+、-、*、/、%
-
類操作符:操作符函數(shù)是類的成員函數(shù)
class Fraction { public: //重載加號操作符 Fraction operator + (const Fraction& other) //operator + 是固定不變的,這里為兩個分數(shù)相加 { Fraction result; result.den = den*other.den; //分母相乘 result.num = num*other.den + other.num*den; //分子交叉相乘 return result; } int num; int den; }; -
全局操作符:需要把操作符函數(shù)聲明為類的朋友
class Fraction { friend Fraction operator + (const Fraction& a,const Fraction& b); public: int num; int den; }; Fraction operator + (const Fraction& a,const Fraction& b) { Fraction result; result.den = a.den*b.den; //分母相乘 result.num = a.num*b.den + b.num*a.den; //分子交叉相乘 return result; }
分數(shù)與整數(shù)相加
class Fraction
{
public:
//Fraction+int
Fraction operator + (int n)
{
Fraction result;
result.num = num + den*n; //分母不變,分子變化
return result;
}
int num;
int den;
};
加法的互換性
上述類操作符寫法只支持了Fraction+int,但互換int+Fraction就不支持了,為此應該考慮使用全局操作符來實現(xiàn)
friend Fraction operator + (int a,const Fraction& b)
賦值操作符=
適用類型:①需要深拷貝時,②需要不同的數(shù)據(jù)類型來賦值時,例如fa=4
賦以不同的類型
注意返回值是this*
class Fraction
{
public:
//Fraction = Fraction
Fraction& operator = (const Fraction& other)
{
this->num = other.num;
this->den = other.den;
return *this;
}
//Fraction = int
Fraction& operator = (int n)
{
this->num = n;
this->den = 1;
return *this;
}
};
需要深拷貝時
p277
相關問題
-
等號的傳導性
返回值必須為return *this
-
等號的自反性
要提前判斷是否為賦值給自己
if(this == &other)return *this //避免賦值給自己
關系操作符==
和算數(shù)運算符寫法差不多
class Fraction
{
public:
bool operator == (const Fraction& other)
{
if(num*other.den == den*other.num)
{
return true;
}
return false;
}
...
};
class Text
{
public:
bool operator == (const char* str)
{
if(strcmp(m_buf,str)==0)
{
return true;
}
}
return false;
...
};
類型轉換操作符()
Fraction fa(2,3);
double value = (double)fa;//錯誤!但可以通過重載操作符實現(xiàn)
class Fraction
{
public:
operator double() //類型轉換操作符比較怪異,不能寫像上面其他類型的一樣寫double operator (),而應該這么寫
{
return (double)num/den;
}
...
};
輸入輸出操作符>>、<<
定義類Logger
Logger lg;
lg << 1;
lg << 1 << "," << 2.0 << "."; //輸出1,2.0.
實現(xiàn)方式
class Logger
{
public:
Logger& operator << (int value)
{
printf("%d",value);
return *this;
}
Logger& operator << (double value)
{
...
}
Logger& operator << (const char* value)
{
...
}
...
}