[英]C++ // Dynamic Memory Allocation
#include <iostream>
using namespace std;
#define SELECT 0
class Z
{
private:
int *z1; int *z2;
public:
Z(const int x1 = 0, const int x2 = 0);
Z(const Z &X);
int *first (void) const {return z1;};
int *second (void) const {return z2;};
~Z(void);
};
Z::Z(const int x1,const int x2){
z1 = new int(x1);
z2 = new int(x2);
}
#if SELECT == 1
Z::Z(const Z &X){
z1 = new int(*X.first() );
z2 = new int(*X.second() );
}
#else
Z::Z(const Z &X){
z1 = X.first();
z2 = X.second();
}
#endif
Z::~Z(){
delete z1;
delete z2;
}
int main()
{
Z firstZ;
Z secondZ(4,7);
Z thirdZ(secondZ);
Z *zp;
zp = new Z(3,5);
Z a(6, *(zp->first() ) ), b=a, c(0,0);
c = *zp;
cout << "Content of c: " << *c.first() << " and " << *c.second() << endl;
delete zp;
cout << "Content of c: " << *c.first() << " and " << *c.second() << endl;
return 0;
}
你好我有這個代碼,當我運行它時我得到
Content of c: 3 and 5
Content of c: 14900448 and 5
但是我期待類似的東西
Content of c: 3 and 5
Content of c: Garbage and Garbage
但是不知何故 c.second 仍然指向值 5。你能解釋一下這是如何發生的嗎?
我也想知道以下內容:當我評論(或刪除)這些行時
Z firstZ;
Z secondZ(4,7);
Z thirdZ(secondZ);
再次運行我得到了我的預期
Content of c: 3 and 5
Content of c: 1924224 and 1907344
你能解釋一下這是怎么發生的嗎?
謝謝
但是不知何故 c.second 仍然指向值 5。你能解釋一下這是如何發生的嗎? ......當我評論(或刪除)這些行時......我得到了我的期望......你能解釋一下這是怎么發生的嗎?
當您的程序有未定義的行為時,您可能會看到這種情況。
啟用或禁用優化、更改不相關的行(就像您在這種情況下所做的那樣)、更改編譯器版本等,都可能導致您的程序輸出“垃圾”,或者看起來不像 garbase 的東西,或者崩潰。
除非您單步執行生成的代碼,否則無法知道結果會是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.