我正在学习 C++ 作为一种爱好,并且正在努力使用“new”来动态创建类对象。我读过动态创建的类不会丢失范围,但这似乎不适用于我的简单示例。
执行时,'testValue1' 的值在构造函数中设置为 555 并打印。当控制返回到 main 时,'testvalue' 不幸地设置为 0(或未定义 - 不确定)。我可以在 main 内部设置值,并且在 main 内部以及 for 循环中正确维护该值。
问题:我不明白为什么当控制返回给main时,555的初始化值没有保持。我知道我做错了什么或者没有正确理解动态分配的类对象的范围......感谢任何帮助。这是示例代码:
//main.cpp
#include <iostream>
using namespace std;
class generalVars
{
private:
public:
//data attributes
int testValue1;
//constructor
generalVars()
{
cout << "I am in general vars constructor" << endl;
int testValue1= 555;
cout << "testValue1 has been set " << testValue1 << endl;
}
~generalVars(void)
{
cout << "I am in general vars destructor" << endl;
};
};
int main(int argc, char *argv[])
{
cout << "I am in Main" << endl;
generalVars* myGeneralVars = new generalVars; //create on heap
cout << "Main1 testvalue1 = " << myGeneralVars->testValue1 << endl;
myGeneralVars->testValue1 = 777;
cout << "Main2 testvalue1 = " << myGeneralVars->testValue1 << endl;
for (int i=0; i<= 3; i++)
{
cout << "Inside while loop..." << endl;
cout << "Main3 " << i << " testvalue1 = " << myGeneralVars->testValue1 << endl;
}
delete myGeneralVars; //delete from heap
return 0;
}
最佳答案
这个声明:
int testValue1= 555;
声明一个局部变量,与同名的数据成员不同。
所以它不会改变成员的值。
相反,做例如
testValue1= 555;
或者使用构造函数的内存初始化列表,像这样:
generalVars()
: testValue1( 555 )
{
cout << "I am in general vars constructor" << endl;
cout << "testValue1 has been set " << testValue1 << endl;
}
关于c++ - 使用 new 创建的对象的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257444/