1

嘿,所以我对 C++ 还很陌生,我不确定为什么这不起作用。我有两个类,我们称它们为 ned 和 myfile。我需要在每个 ned 对象中有两个文件对象。这是一个简化:

class myfile {
  public:
      int nData;
      int nHeaderSize;

  myfile() {
    nData=0;
    nHeaderSize=0;
  }
};

class ned {
  public:
    myfile *pSrc,*pTgt;

  ned() {
   myfile* pSrc = new myfile();
   myfile* pTgt = new myfile();
  }
};

int main(int argc, char* argv[]) {
  ned* nedObj = new ned();
  nedObj->pSrc->nData=5; //Access violation error here
}

这显然是一个简化版本,但任何想法都值得赞赏。如果从这个小例子中问题不明显,我可以添加更多代码。

编辑:修复了我在翻译成较小示例时输入错误的分号

4

4 回答 4

4

改变

ned() {
  myfile* pSrc = new myfile();
  myfile* pTgt = new myfile();
}

ned()
: pSrc(new myfile),
  pTgt(new myfile) {
}

目前,您的代码未初始化nedObj. 相反,的构造函数创建了两个名为和ned的局部变量。变量立即超出范围,导致资源泄漏。pSrcpTgt

于 2013-08-13T18:58:24.510 回答
3
class ned {
  public:
    myfile *pSrc;*pTgt;

  ned() {
   myfile* pSrc = new myfile();
   myfile* pTgt = new myfile();
  }
};

应该:

class ned {
  public:
    myfile *pSrc;*pTgt;

  ned() {
   this->pSrc = new myfile();
   this->pTgt = new myfile();
  }
};
于 2013-08-13T18:58:48.700 回答
0

我继续为你修好了

class myfile {
public:
  int nData;
  int nHeaderSize;

myfile() {
  nData=0;
  nHeaderSize=0;
  }
}; **//missing semicolon here**

class ned {
public:
  myfile *pSrc, *pTgt; **//was myfile *pSrc;*pTgt, needed a coma instead**

ned() {
 myfile* pSrc = new myfile();
 myfile* pTgt = new myfile();
  }
}; //missing semicolon here

int main(int argc, char* argv[]) {
   ned* nedObj = new ned();
   nedObj->pSrc->nData=5; **//Access violation error here**
}
于 2013-08-13T19:11:20.543 回答
-1

Change the constructor to this:

ned() {
 pSrc = new myfile(); // pSrc is an already defined member.
 pTgt = new myfile(); // Same for pTgt.
}

If you use myfile* pSrc, you are a declaring a new variable that is not the same as the pSrc member variable. Also remember to free the memory:

~ned()
{
delete pSrc; 
delete pTgt;
}
于 2013-08-13T19:03:24.737 回答