前置加加重载
前置加加有返回值,《可以作为左值》,可以连续赋值《返回对象的引用》
以成员函数为例 如果直接返回对象
#include <iostream>
using namespace std;
class points
{
private:
int x;
int y;
public:
points(int x, int y);
void display();
//前置加加有返回值,所以可以作为左值,所以返回值不设置为const 。而是让对象直接自增,所以返回值类型不再是基本数据类型,
points operator++();
};
points::points(int x = 0, int y = 0) : x(x), y(y){};
void points::display()
{
cout << "x: " << this->x << "y: " << this->y;
};
points points::operator++()
{
return points(this->x++, this->y++); //若不需要连续赋值,则返回临时对象类型
}
void test1(points &p1)
{
++p1;
p1.display();
cout << endl;
}
void test2(points &p1)
{
++p1 = points(55, 55); //用匿名对象直接赋值
p1.display();
}
int main()
{
points p1(22, 33);
test1(p1); //演示前置加加的作用
cout << "p1对象的值为:" << endl;
p1.display();
cout << endl;
test2(p1); //演示前置加加能否被连续赋值。
//补充说明: 返回值为对象时,会调用拷贝构造函数,而拷贝构造函数的原型 person(const person &new_object); 对象就是传引用,所以对象的值在执行完test1 函数之后,就改变了。
//这可以从
//当返回值不为对象引用类型时,无法做到连续赋值的情况.
}
返回对象引用的情况
(因为连续赋值的关系,每次返回,返回值必定是作为左值,就像 ++a=b; ++a先运算,返回a+1,然后a+1 继续作为左值,左值一定不能为临时变量,所以一定不能返回临时对象。)
#include <iostream>
using namespace std;
class points
{
private:
int x;
int y;
public:
points(int x, int y);
void display();
//前置加加有返回值,所以可以作为左值,所以返回值不设置为const 。而是让对象直接自增,所以返回值类型不再是基本数据类型,
points &operator++();
};
points::points(int x = 0, int y = 0) : x(x), y(y){};
void points::display()
{
cout << "x: " << this->x << "y: " << this->y;
};
points &points::operator++()
{
this->x++;
this->y++;
return *this;
// return points(this->x++, this->y++);若不需要连续赋值
// 1-允许进行连续赋值
// 2- 防止返回对象(返回对象也可以进行连续赋值(常规的情况,如a = b = c,而不是(a = b) = c))的时候调用拷贝构造函数和析构函数导致不必要的开销,降低赋值运算符的效率。
}
void test1(points &p1)
{
++p1;
p1.display();
}
void test2(points &p1)
{
++p1 = points(55, 55); //用匿名对象直接赋值
p1.display();
}
int main()
{
points p1(22, 33);
test1(p1);//演示前置加加的作用
test2(p1);//演示前置加加能否被连续赋值。
}