歡迎您光臨本站 註冊首頁

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

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
#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");
}


[火星人 ] 拷貝構造函數 北郵問題破解已經有325次圍觀

http://coctec.com/docs/security/show-post-58909.html