Main.cpp
#include <string>
#include "Test.h"
#include "Test.cpp"
using namespace std;
using namespace Classes;
int main(int argc, char** argv) {
Test test("bar");
return 0;
}
测试文件
#include "Test.h"
namespace Classes {
class Test::Implementation {
string mFoo;
friend class Test;
};
Test::Test(string foo) {
setFoo(foo);
i = new Test::Implementation();
}
Test::~Test() {
}
string Test::getFoo() {
return i->mFoo;
}
void Test::setFoo(string foo) {
i->mFoo = foo;
}
}
测试
#ifndef TEST_H
#define TEST_H
using namespace std;
namespace Classes {
class Test {
private:
class Implementation;
Implementation *i;
public:
friend class Implementation;
Test(string foo);
~Test();
string getFoo();
void setFoo(string foo);
};
}
#endif
我正在尝试使用C ++中的嵌套类。
当我编译该应用程序时,出现一个问题:“ Main.exe已停止工作”
我找不到问题。但是我知道我的应用程序崩溃了,然后尝试执行
i->mFoo
。也许有人知道如何解决这个问题? 最佳答案
在Test::Test()
构造函数中,您是在初始化setFoo()
之前调用i
的,因此i
当时尚未初始化,尝试取消引用未初始化的指针会导致崩溃。只需将这两行交换,以便首先初始化i
。
您还需要将delete i;
添加到Test::~Test()
析构函数中,否则i
的内存将被泄漏。
关于c++ - 嵌套类崩溃C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33366481/