当 class 成员函数执行时程序停止工作

Program stops working when class member function executes

我知道 class 成员函数有问题,因为我将它们中的所有内容注释掉,程序将 运行 正常,但是当我取消注释任何内容时它停止工作。构造函数 运行 也很好。

这是我的 CharArray.h 文件:

#ifndef CHARARRAY_H
#define CHARARRAY_H

class CharArray
{
private:
    char * pArray;
    int iSize;

public:
    CharArray(int size)
    {
        char *pArray = nullptr;
        iSize = size;
        pArray = new char[iSize];
        pArray = '[=11=]';
    }

    void setItem (int loc, char ch);
    char getItem (int loc);

    ~CharArray()
    {
        delete [] pArray;
    }
};

#endif // CHARARRAY_H

这是我的成员函数:

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include "CharArray.h"
using namespace std;

void CharArray::setItem (int loc, char ch)
{

    pArray[loc] = ch;

    cout << pArray[loc] << endl;

  return;
}

char CharArray::getItem (int loc)
{
  char c;

    c = pArray[loc];

  return c;
}

这是我的主要文件:

#include <iostream>
#include <iomanip>
#include "CharArray.h"
using namespace std;

int main()
{
    CharArray myChar (5);
    int size;
    char cstr[10] = "Drew";

    myChar.setItem(1, 'A');

    char c = myChar.getItem(5);
    cout << c << endl;

return 0;
}

你的第一个问题在构造函数中:

CharArray(int size)
{
    char *pArray = nullptr;   // <-- unrelated to the pArray in the object!
    iSize = size;
    pArray = new char[iSize];
    pArray = '[=10=]';            // <-- we just lost the handle to new array
}

最后一行应该是:

    *pArray = '[=11=]';

此外,最好使用更现代的构造函数样式,例如:

CharArray(int size)
     : pArray(new char[size]),
       iSize(size)
{
    *pArray = '[=12=]';
}