嘿,所以我对C++相当陌生,我不知道为什么这不起作用。我有两门课,我们叫他们内德和我的档案。我需要在每个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
}这显然是一个简化的版本,但任何想法都是可取的。如果这个小例子中的问题不明显,我可以添加更多的代码。
编辑:修正分号,当我翻译到较小的例子时,我输入错误。
发布于 2013-08-13 18:58:24
变化
ned() {
myfile* pSrc = new myfile();
myfile* pTgt = new myfile();
}至
ned()
: pSrc(new myfile),
pTgt(new myfile) {
}目前,您的代码不初始化nedObj。相反,ned的构造函数创建了两个名为pSrc和pTgt的局部变量。
发布于 2013-08-13 18:58:48
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-13 19:11:20
我先帮你修好了
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**
}https://stackoverflow.com/questions/18216986
复制相似问题