代码在成员函数中的单次迭代后终止,该函数为循环中的指针赋值

问题描述

我正在创建一个抽象数据类型。代码如下

#include <iostream>
using namespace std;

template <class T>
class cArray
{
    int size;
    T* p;

public:
    cArray(int size)
    {
        this -> size = size;
        T* p = new T[size];
    }

    void setval(void)
    {
        for (int i=0; i<size; i++)
        {
            cout << "enter value at index " << i << endl;
            // cin >> *(p+i);
            cin >> p[i];
        }
    }

    void disp(void)
    {
        for (int i=0; i<size; i++)
        {
            cout << *(p+i) <<endl;
        }
    }
    
};

int main()
{
    cArray <float> obj(5);
    obj.setval();
    obj.disp();
    return 0;
}

其中 setval 设置数组中的值,disp 显示其中的元素。

但是,代码setval 中的单次迭代后终止。我不确定如何解决这个问题,因为它的指针算术似乎是正确的。请提出更改建议。

解决方法

接近拼写错误,但我的 Clang 编译器直接在错误处停止并发出警告

未使用的变量'p'

cArray ctor中。

让我们看看它:

cArray(int size)
{
    this -> size = size;       // ok this correctly assign to the member
    T* p = new T[size];        // Oops,this assigns to a local variable...
}

解决方法很简单:p = new T[size]; 或者如果您希望成员身份更加明确:this->p = new T[size];

但要注意:您正在 ctor 中进行分配。这意味着您应该在析构函数中取消分配,并且您应该删除复制/移动构造函数/赋值运算符或构建自定义实现。

,

您的构造函数未初始化成员 p。当您稍后读取该值并尝试间接通过它时,程序的行为将是未定义的。