1,
赋值运算符重载返回的是个引用,重载+运算符返回的也是个引用,所以都没有调用拷贝函数
#include<iostream>
using namespace std;
class point{
private:
int x,y;
public:
point(int x=0,int y =0);
~point(){
cout<<"我是析构"<<"("<<x<<","<<y<<")"<<endl;
}
point(point & p){
x = p.x;
y = p.y;
cout<<"我是拷贝"<<"("<<x<<","<<y<<")"<<endl;
}
point & operator =(const point &p){
if(this!=&p){
x = p.x;
y = p.y;
cout<<"我是赋值"<<endl;
}
return *this;
}
friend point operator +(point &p1,point &p2);
point &operator +(point &p1){
x = x+p1.x;
y =y+p1.y;
return *this;
}
};
// point operator +(point &p1,point &p2){
// point temp(1,1);
// temp.x = p1.x+p2.x;
// temp.y = p1.y+p2.y;
// return temp;
// }
point::point(int newx,int newy){
x = newx;
y = newy;
cout<<"我是构造"<<"("<<x<<","<<y<<")"<<endl;
}
int main(){
point p1(1,2);
point p2(2,3);
point p3(0,0);
p3 = p1.operator+(p2);
return 0;
}
2,
重载赋值运算符那没有&,返回一个point对象,所以要调用拷贝函数,
#include<iostream>
using namespace std;
class point{
private:
int x,y;
public:
point(int x=0,int y =0);
~point(){
cout<<"我是析构"<<"("<<x<<","<<y<<")"<<endl;
}
point(point & p){
x = p.x;
y = p.y;
cout<<"我是拷贝"<<"("<<x<<","<<y<<")"<<endl;
}
point operator =(const point &p){
if(this!=&p){
x = p.x;
y = p.y;
cout<<"我是赋值"<<endl;
}
return *this;
}
friend point operator +(point &p1,point &p2);
point &operator +(point &p1){
x = x+p1.x;
y =y+p1.y;
return *this;
}
};
// point operator +(point &p1,point &p2){
// point temp(1,1);
// temp.x = p1.x+p2.x;
// temp.y = p1.y+p2.y;
// return temp;
// }
point::point(int newx,int newy){
x = newx;
y = newy;
cout<<"我是构造"<<"("<<x<<","<<y<<")"<<endl;
}
int main(){
point p1(1,2);
point p2(2,3);
point p3(0,0);
p3 = p1.operator+(p2);
return 0;
}
3,
都不加&时
#include<iostream>
using namespace std;
class point{
private:
int x,y;
public:
point(int x=0,int y =0);
~point(){
cout<<"我是析构"<<"("<<x<<","<<y<<")"<<endl;
}
point(point & p){
x = p.x;
y = p.y;
cout<<"我是拷贝"<<"("<<x<<","<<y<<")"<<endl;
}
point operator =(const point &p){
if(this!=&p){
x = p.x;
y = p.y;
cout<<"我是赋值"<<endl;
}
return *this;
}
friend point operator +(point &p1,point &p2);
point operator +(point &p1){
x = x+p1.x;
y =y+p1.y;
return *this;
}
};
// point operator +(point &p1,point &p2){
// point temp(1,1);
// temp.x = p1.x+p2.x;
// temp.y = p1.y+p2.y;
// return temp;
// }
point::point(int newx,int newy){
x = newx;
y = newy;
cout<<"我是构造"<<"("<<x<<","<<y<<")"<<endl;
}
int main(){
point p1(1,2);
point p2(2,3);
point p3(0,0);
p3 = p1.operator+(p2);
return 0;
}