接上篇文章https://blog.csdn.net/Master_Cui/article/details/109515571继续实现分数类和相关运算符的重载
6.自增自减运算符(++ --)的重载
因为内置类型的++ --分为前置类型和后置类型,所以,重载++和--时,也要区分前置和后置类型,而且,因为++和--会更改对象的状态,所以,应该把++和--定义为成员函数
为了和内置类型的++和--保持一致,前置++ --运算符应该返回对象类型的引用(直接得到++ --运算符后的对象),而后置++ --类型应该返回对象的副本(获得++ --运算符之前的对象或者值)
因为前置和后置的++和--的函数名都是operator++或者operator--,无法区分前置和后置的版本,所以,为了区分前置和后置的++--的版本,需要在后置版本的形参列表中加个int形参,该int形参的作用就是区分++和--的前置后置版本,不参与运算
fraction类的++和--的实现代码及测试如下
fraction &fraction::operator++()
{
cout<<"operator++()"<<endl;
this->numerator_+=this->denominator_;
return *this;
}
fraction &fraction::operator--()
{
cout<<"operator--()"<<endl;
this->numerator_-=this->denominator_;
return *this;
}
fraction fraction::operator++(int)
{
cout<<"operator++(int)"<<endl;
fraction t(*this);
++*this;
return t;
}
fraction fraction::operator--(int)
{
cout<<"operator--(int)"<<endl;
fraction t(*this);
--*this;
return t;
}
int main(int argc, char const *argv[])
{
fraction t1(10,20),t2(-5,-10), t3(15,20), t4(-1, 30);
cout<<--t1<<endl;
cout<<++t2<<endl;
cout<<t3--<<endl;
cout<<t4++<<endl;
return 0;
}
运算结果正确,测试OK
上述代码中后置类型的++ --会依靠前置的++ --来实现
7.函数调用运算符的重载
如果一个类定义了函数调用运算符,那么就可以像调用函数一样使用该类的对象,这样类的对象也叫函数对象,函数调用运算符必须是成员函数,因为是和类绑定的。函数对象的返回值和形参没有硬性规则。函数调用运算符主要是用在一些需要传入函数对象实参的容器、泛型算法等
在分数类fraction中,定义了一种求取分数倒数的函数调用运算符。
fraction fraction::operator()(const fraction ¶)
{
cout<<__func__<<endl;
fraction t;
t.numerator_=para.denominator_;
t.denominator_=para.numerator_;
cout<<t<<endl;
return t;
}
int main(int argc, char const *argv[])
{
fraction t1(10,20),t2(-5,-10), t3(15,20), t4(-1, 30);
std::vector<fraction> vf;
vf.push_back(t1);
vf.push_back(t2);
vf.push_back(t3);
vf.push_back(t4);
fraction func;
for_each(vf.begin(), vf.end(), func);
return 0;
}
输出结果正确,测试OK
注意,一定要使用类的对象来调用operator(),不能用类名来调用operator(),否则将调用拷贝构造函数...
8.类型转换运算符的重载
类型转换运算符很特殊,可以把一个类转换为除了void之外的任意类型
函数格式如下
operator type() const
type表示某种类型,该函数没有返回值,也没有形参,通常,一个类转为bool较为常见,而在调用类型转换运算符时,有可能出现隐式类型转化,所以,通常在在函数声明时,在函数名前面加explicit。
在fraction类中,类型转换运算符用来判断分数是否有效
fraction::operator bool() const
{
cout<<__func__<<endl;
return this->denominator_==0;
}
int main(int argc, char const *argv[])
{
fraction t1(10,20),t2(1,0);
cout<<bool(t1)<<endl;
cout<<bool(t2)<<endl;
return 0;
}
不要过度使用类型转换运算符。
至此,分数类fraction实现完了,完整代码见https://gitee.com/cuijidan/myfraction
参考
《C++ Primer》
欢迎大家评论交流,作者水平有限,如有错误,欢迎指出