C ++如何从成员函数访问变量?

c++ how to access variable from member function?

我有问题。我想对在成员函数中生成的数组的单个元素进行操作,但它不起作用。这是我的代码:

    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;
    }

我怎样才能访问该元素?真正的问题在哪里?谢谢!

问题是,您通过重新声明在函数范围内隐藏了 pole 的名称。将杆子前面的 int * 留在后面,在 generate_pole 中,它应该可以工作。

阴影示例:

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

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

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

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

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