關於拷貝構造函數,類的賦值與複製

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;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章