C++中對象的複製用兩種形式,如下
B b1;
B b2(b1);
或
B b1;
B b2 = b1;
這時類調用的是拷貝構造函數。
而賦值是對“=”運算符的重載。
那點point類爲例:
class Point
{
public:
Point(){}Point(int x,int y){ this.x =x; this.y = y;}Point(const Point &p)//拷貝構造函數{
this.px = p.px;this.py = p.py;
}Point & operator = (const Point &p) ‘=’運算符的重載{
if(this == &p) //檢查是否自己給自己賦值{
return *this;
}
this.px = p.px;this.py = p.py;return *this; //返回本對象的引用
}
private:
int px;int py;
};