【问题标题】:c++ how to access variable from member function?c ++如何从成员函数访问变量?
【发布时间】:2015-12-06 17:31:33
【问题描述】:

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

    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 = new int [10];
  • 然后打开你的编译器警告! gcc -Wall -Wextra...

标签: c++ arrays function member


【解决方案1】:

问题是,您通过重新声明它来在函数范围内隐藏极点的名称。将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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 不会编译,去掉pole = new int [10];前面的*
    • 哈哈。我们将共同发布!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2014-07-29
    • 2023-03-23
    相关资源
    最近更新 更多