嵌套 class 崩溃 C++
Nested class crash C++
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;
}
Test.cpp
#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;
}
}
Test.h
#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 has stopped working"
我找不到问题所在。但我知道我的应用程序崩溃了,然后我尝试做 i->mFoo
。也许有人知道如何解决这个问题?
在 Test::Test()
构造函数中,您在初始化 i
之前调用 setFoo()
,因此此时 i
未初始化,并且尝试取消引用未初始化的指针会导致您碰撞。简单地交换这两行,这样 i
首先被初始化。
您还需要将 delete i;
添加到 Test::~Test()
析构函数中,否则 i
的内存将被泄漏。
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;
}
Test.cpp
#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;
}
}
Test.h
#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 has stopped working"
我找不到问题所在。但我知道我的应用程序崩溃了,然后我尝试做 i->mFoo
。也许有人知道如何解决这个问题?
在 Test::Test()
构造函数中,您在初始化 i
之前调用 setFoo()
,因此此时 i
未初始化,并且尝试取消引用未初始化的指针会导致您碰撞。简单地交换这两行,这样 i
首先被初始化。
您还需要将 delete i;
添加到 Test::~Test()
析构函数中,否则 i
的内存将被泄漏。