作为一名新的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
不幸的是,很多人在生命周期中(当一个对象被创建和销毁时 - 一种运行时概念)混淆了范围(程序中的某个名称是可见的 - 编译时间概念)。但他们非常不同。 –