這是今天早些時候測驗的代碼。語言:C++。結合使用類指針返回垃圾值
class Shape
{
protected:
int *x;
int *y;
public:
void draw()
{
//we were supposed to add random code here.
}
};
我們被要求創建一個我們選擇的重載操作符並在main中實現它。我是一個小的指針嚇倒,所以我決定創建像這樣一個構造函數:
class Shape
{
protected:
int *x;
int *y;
public:
void draw()
{
cout<<*x<<endl;
}
Shape(){};
Shape{int a, int b)
{
x = &a; //this I thought would allow *x to act just like a normal variable.
y = &b;
}
//code for operator overloading.
};
我是我當時一桿進洞測驗的印象,但是當我繼續,並試圖執行它我在家裏的電腦上,我意識到繪圖函數會返回垃圾值/內存地址。其他一切都因此而受損。你能告訴我爲什麼會發生這種情況嗎?它是否與指針的範圍有關?我想能夠使用指針作爲常規變量。只是一個學生。提前致謝!
'x =&a;'將臨時地址賦給'x'。構造函數完成後'a'不存在。搖晃指針。 – 2013-05-13 14:34:28
對不起。這是C++。 – 2013-05-13 14:37:45
好的 - 我現在已經修復了您的代碼。 – 2013-05-13 14:41:47