我有一个问题。我想对在成员函数中生成的数组的单个元素进行操作,但它不起作用。这是我的代码:
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++ 标准库为您处理所有内存。
关于C++如何从成员函数访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501703/