作爲一名新的C++愛好者,我仍在努力理解使用「新」創建的類對象的範圍。我認爲我通過使用「new」實例化動態對象來讀取該類,因此類(和成員)可以被程序的所有部分直接訪問(例如,在其他函數內),因爲它不是在堆棧上創建的。使用「新」的類範圍
在下面的代碼中,我在構造函數中將'tesValue1'的初始值設置爲「111」,然後嘗試在「check_accessibility」函數中將其更新爲「222」。這不能編譯錯誤「myGeneralVars」沒有在這個[函數調用]範圍內聲明。
任何幫助,非常感謝。
//main.cpp
#include <iostream>
using namespace std;
class generalVars
{
private:
public:
//data attributes
int testValue1;
//constructor
generalVars()
{
testValue1= 111;
}
~generalVars(void)
{
cout << "destructor code here" << endl;
};
};
void check_accessibility() {
myGeneralVars->testValue1= 222;
}
int main(int argc, char *argv[])
{
generalVars* myGeneralVars = new generalVars; //create on heap
cout << "Main testvalue1 = " << myGeneralVars->testValue1 << endl; //value set in constructor
check_accessibility(); //sets testValue to new value
cout << "Main testvalue1 = " << myGeneralVars->testValue1 << endl; //want "222"
delete myGeneralVars; //delete from heap
return 0;
}
誰使用的措辭做了一個可怕的工作。它的*可訪問性*不是在玩什麼;它的對象的**生命**。唯一未完成的對創建對象的引用仍然只在局部變量中。 – WhozCraig
不幸的是,很多人在生命週期中(當一個對象被創建和銷燬時 - 一種運行時概念)混淆了範圍(程序中的某個名稱是可見的 - 編譯時間概念)。但他們非常不同。 –