我正在做一個快速測驗,看看如何將動態分配的私有資料成員的值獲取到類之外的另一個動態分配的變數,但我無法回傳它們的值。每當我嘗試時,都會在運行時導致分段錯誤。我一直在慢慢簡化代碼,甚至簡化為 int 資料型別,我無法讓它作業。這是代碼:
#include <iostream>
class testing{
public:
testing();
int getValue();
private:
int* asdf;
};
int main(){
int* test = NULL;
int test2, test3;
testing test1;
test2 = test1.getValue();
test = new int(test2);
test3 = *test;
std::cout << test3 << std::endl;
return 0;
}
testing::testing(){
int* asdf = new int(3);
}
int testing::getValue(){
return *asdf;
}
我希望代碼只列印出 3,但事實并非如此。我在搞砸什么?
uj5u.com熱心網友回復:
這里存在空指標參考問題。分配一些記憶體并初始化test或使test其他一些 int 點。
編輯:正如@songyuanyao 所指出的,建構式沒有初始化 original testing::asdf,而是新的區域變數asdf。您還應該洗掉int*說明符以避免該問題。
int main(){
int* test = NULL; //null pointer. You did not give any valid address.
int test2, test3;
testing test1;
test2 = test1.getValue();
test = new int(test2);
test3 = *test; //ERROR! Trying to dereference the null pointer
std::cout << test3 << std::endl;
return 0;
}
testing::testing(){
asdf = new int(3); // removed int*, as original expression does hide your member variable.
}
此外,裸new運算式容易產生記憶體泄漏問題。我建議您熟悉 C 中的智能指標。
uj5u.com熱心網友回復:
您在 getValue 訪問器函式中獲得了一半的解決方案 - 嘗試實作一個 mutator 函式來修改asdf而不是呼叫new的testing建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435746.html
