拷貝構造函數 北郵問題破解

#include <iostream>  
using namespace std;  
class Point    //Point 類的聲明  
{  
public:    //外部接口  
      Point(int xx=0, int yy=0) {X=xx;Y=yy;}    //構造函數  
      Point(Point &p);    //拷貝構造函數  
      int GetX() {return X;}  
      int GetY() {return Y;}  
private:    //私有數據  
      int X,Y;  
};  
    
//成員函數的實現  
Point::Point(Point &p)  
{  
      X=p.X;  
      Y=p.Y;  
      cout<<"拷貝構造函數被調用"<<endl;  
}  
    
//形參爲Point類對象的函數  
void fun1(Point p)  
{    cout<<p.GetX()<<endl;  
}  
    
//返回值爲Point類對象的函數  
Point fun2()  
{  
      Point A(1,2);  
      return A;  
}  
    
//主程序  
int main()  
{  
      Point A(4,5);    //第一個對象A  
      Point B(A);                  //情況一,用A初始化B。第一次調用拷貝構造函數  
      cout<<B.GetX()<<endl;  
      fun1(B);  //情況二,對象B作爲fun1的實參。第二次調用拷貝構造函數  
      B = fun2();  //情況三,函數的返回值是類對象,函數返回時,調用拷貝構造函數  
           cout<<B.GetX()<<endl;  
    
      return 0;  
}  
DEV環境
 
 
正解:
Point(Point &p)這個構造函數要求的是左值,而你傳進去的是右值,所以說類型不匹配。
所謂左值對象,可以理解爲能放在賦值號左邊的對象。
改成Point(const Point &p)或者Point(Point p)就過了,因爲這兩種形式匹配參數是右值。
--
改後:
#include<iostream>
using namespace std;
class Point
{
public:
        Point(int xx,int yy)
        {
                  X=xx;
                  Y=yy;
        }
        Point(const Point &p);
        int GetX(){return X;}
        int GetY(){return Y;}
private:
        int X,Y;
};
Point::Point(const Point &p)
{
        X=p.X;
        Y=p.Y;
        cout<<"拷貝構造函數被調用"<<endl;
}
void fun1(Point p)
{
     cout<<p.GetX()<<endl;
}
Point fun2(void)
{
      Point A(1,2);
   
      return A;
}
int main()
{
    Point A(4,5);
    Point B(A);
   
    cout<<B.GetX()<<endl;
    fun1(B);
   
    B=fun2();
    cout<<B.GetX()<<endl;
   
    system("pause");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章