#include <stdio.h> #include <iostream.h> //using namespace std; class Point { public: Point() { m_x = 0; m_y = 0; cout<<"construct: x = "<<m_x<<" y = "<<m_y<<endl; } Point(unsigned int x, unsigned int y) { m_x = x; m_y = y; cout<<"construct: x = "<<m_x<<" y = "<<m_y<<endl; } void print() { cout<<"x = "<<m_x<<endl; cout<<"y = "<<m_y<<endl; cout<<endl; } Point(const Point& p):m_x(p.m_x),m_y(p.m_y){ cout<<"copy construcor of this from p:(m_x="<<p.m_x<<",m_y="<<p.m_y<<")"<<endl; } ~Point(){ cout<<"~Point():x="<<m_x<<"y="<<m_y<<endl; } friend Point operator+(Point& pt, int nOffset); friend Point operator+(int nOffset, Point& pt); public: unsigned int m_x; unsigned int m_y; }; Point operator+(Point& pt, int nOffset) { //Point temp=pt;//等同于Point temp(pt);初始化是调用拷贝构造函数滴。 Point temp; temp = pt;//调用赋值操作符 temp.m_x += nOffset; temp.m_y += nOffset; printf("where/n"); return temp; } int main(int argc, char* argv[]) { Point pt(10, 20); cout<<"+++++++++++++++++++++"<<endl; Point& ptt= pt+3; //这里加不加&(即Point ptt= pt+3似乎没影响),似乎结果都一样,这里有点不明白,请大家指教 ptt.print(); cout<<"+++++++++++++++++++++"<<endl; pt=pt+4; pt.print(); cout<<"+++++++++++++++++++++"<<endl; pt = pt + 1; getchar(); return 0; } /* 通过对程序3进行单步调试发现:运行结果如下 我的理解如下:有什么不妥的地方,请多多指教 construct: x = 10 y = 20 //pt构造 +++++++++++++++++++++ construct: x = 0 y = 0 //temp构造 where copy construcor of this from p:(m_x=13,m_y=23) //生成临时对象 ~Point():x=13y=23 //析构temp x = 13 y = 23 +++++++++++++++++++++ construct: x = 0 y = 0 //temp构造 where copy construcor of this from p:(m_x=14,m_y=24) //生成临时对象 ~Point():x=14y=24 //析构temp ~Point():x=14y=24 //析构临时对象,由于这里没有被赋值给另一个对象 x = 14 y = 24 +++++++++++++++++++++ construct: x = 0 y = 0 //temp构造 where copy construcor of this from p:(m_x=15,m_y=25) //生成临时对象 ~Point():x=15y=25 //析构temp ~Point():x=15y=25 //析构临时对象,由于这里没有被赋值给另一个对象 ~Point():x=13y=23 //析构ptt ~Point():x=15y=25 //析构最初的pt */