前言
在上一则教程中,适合我们讲述了重载运算符中前 ++和后++的具备C教重载函数的实现,阐述了在 C++中可以将运算符进行重载的语言基方法,这种方法大大地便利了程序员编写代码,础的程在接下来地叙述中,适合我们将着重讲述运算符重载时地一些更为细致地内容,具备C教其中就包括当重载地运算符返回值为引用和非引用两种状态时,语言基代码执行效率地高低以及采用在类内实现运算符重载函数的础的程方法。
返回值为引用和非引用的高防服务器适合区别
在上述所示的类当中,增加一部分代码,具备C教加入析构函数以及拷贝构造函数,语言基代码如下所示:
class Point { private: int x; int y; public: Point() { cout<<"Point()"<<endl; } Point(int x,础的程 int y) : x(x), y(y) { cout<<"Point(int x, int y)"<<endl; } Point(const Point& p) { cout<<"Point(const Point& p)"<<endl; x = p.x; y = p.y; } ~Point() { cout<<"~Point()"<<endl; } friend Point operator++(Point &p); friend Point operator++(Point &p, int a); void printInfo() { cout<<"("<<x<<", "<<y<<")"<<endl; } };在上述的代码中,我们在构造函数以及拷贝构造函数析构函数都加入了打印信息,适合其中,具备C教运算符重载函数前++和后++函数沿用之前的语言基一样,返回值不是引用,与此同时,云南idc服务商我们在前 ++和后 ++函数中也加入打印信息的代码,代码如下所示:
/* ++p */ Point operator++(Point &p) { cout << "++p" << endl; p.x += 1; p.y += 1; return p; } /* p++ */ Point operator++(Point &p, int a) { cout << "p++" << endl; Point n; n = p; p.x += 1; p.y += 1; return n; }上述便是前 ++和 后 ++的重载函数,紧接着,书写主函数的代码,观察当返回值为非引用的时候,代码的运行效果,主函数代码如下所示:
int main(int argc, char **argv) { Point p1(1, 2); cout<<"begin"<<endl; ++p1; cout << "