c++如何从成员函数中访问变量

c++ how to access variable from member function?

本文关键字:访问 变量 函数 成员 c++      更新时间:2023-10-16

我有一个问题。我想操作一个数组的单个元素,这是在成员函数中生成的,但它不工作。下面是我的代码:

    using namespace std;
    class Example
    {
    public:
        int *pole;
        void generate_pole();
    };
    void Example::generate_pole()
    {
        int *pole = new int [10];
        for (int i = 0; i < 10; i++)
        {
            pole[i] = i;
        }
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        Example reference;
        reference.generate_pole();
        cout << reference.pole[1] << endl;          //there is the problem
        system("pause");
        return 0;
    }

如何访问元素?真正的问题在哪里?谢谢你!

int *pole = new int [10];正在本地范围内创建一个同名的变量pole。这是遮蔽成员变量。

修复,从错误行中删除int*: pole = new int [10];

也就是说,在这种情况下,我倾向于使用构造函数来设置成员变量:当然,您应该默认将pole初始化为nullptr。这样,当类的实例超出作用域时,您可以在析构函数delete[] pole。否则你的代码会像漏水器一样泄漏内存。

另一种方法是使用std::vector<int> pole;,并让c++标准库为您处理所有内存

问题是,通过重新声明pole的名称,您在函数的作用域中遮蔽了它。在generate_pole中,把int *放在杆子前面,它应该可以工作。

使用阴影的示例:

int i = 0; // i is 0
std::cout << "before scope: " << i << std::endl; // prints 0
{ 
    int i = 1; 
    std::cout << "inside scope: " << i << std::endl; // prints 1
}
std::cout << "behind scope: " << i << std::endl; // prints 0