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;
}
如何访问元素?真正的问题在哪里?谢谢你!
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
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 通过按地址访问变量
- 通过 get-Method 访问变量在类外不起作用
- 是否可以使用指针访问变量以避免直接编辑变量?
- 我无法访问变量的值,即使我通过范围传递了它
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- (C++) 从另一个类访问变量时值无效
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 是否可以从字符串访问变量?
- 变量 z 无法从其他函数访问变量 x
- 如何在 C++ 中从 void 返回函数访问变量
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 从函数中删除动态内存分配,但无法访问变量
- 如何从派生类中的基类访问变量的值?
- 如何通过指针更快地访问变量,然后直接访问变量?
- 如何在公共类 c++ 中访问变量的值
- 从 Visual Studio 中的多个源文件访问变量
- 使用命名空间和模板类访问变量
- 从子对话框访问变量