c++ - 使用 new 创建的对象的范围

标签 c++ named-scope

我正在学习 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/

相关文章:

c++ - 如何在boost中使用digamma函数

java - 是否有查询 HTML 表的 SQL 包装器

c++ - C++从文件中读取数据

sql - 为什么这个 Rails 命名范围返回空(未初始化?)对象?

ruby-on-rails - Rails name_scope 忽略急切加载

ruby-on-rails - 如何使 named_scope 与连接表一起正常工作?

c++ - 这些编程语言的 headless 浏览器库

c++ - 在 Visual Studio 2012 中使用 Gstreamer

ruby-on-rails-3 - named_scope 和 .first?

ruby-on-rails - 使用上下文在 Rails 中链接范围的问题