C++ 嵌套类崩溃C++;

C++ 嵌套类崩溃C++;,c++,class,nested,C++,Class,Nested,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; } 测试h #ifndef TEST_H #define TEST_H using namespace s

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;
}
测试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已停止工作” 我找不到问题。但我知道我的应用程序崩溃了,然后我尝试做
I->mFoo
。也许有人知道如何解决这个问题?

在初始化
i
之前,在
Test::Test()
构造函数中调用
setFoo()
,因此
i
在该点未初始化,尝试取消对未初始化指针的引用会导致崩溃。只需交换这两行,以便首先初始化
i


您还需要添加
删除i
测试::~Test()
析构函数,否则
i
的内存将泄漏。

您没有为
类实现提供声明只有一个转发声明。是时候加载调试器了。顺便说一句,不清楚为什么不让测试类成为一个抽象接口,然后在Test_实现中实现所有东西,这是从该接口派生的。这看起来是向测试类用户隐藏实现的典型方式。我假设您的实际用例更复杂,否则只考虑使用接口。
#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