2015-10-27 103 views
0

Main.cpp的嵌套类崩溃C++

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

+0

您没有提供'class Implementation'声明;'只有前向声明。 –

+2

加载调试器的时间。 –

+0

顺便说一句,不清楚为什么你不会只是让Test类成为一个抽象接口,然后在Test_Implementation中实现所有的东西,它是从该接口派生的。这对于从Test类的用户隐藏实现看起来很典型。我将假设你的实际用例更复杂 - 否则就考虑使用接口。 – noonex

回答

2

Test::Test()构造函数初始化i之前,您呼叫setFoo(),所以i在这一点上未初始化,并试图取消引用未初始化的指针导致您的崩溃。只需交换这两行,以便首先初始化i

您还需要将delete i;添加到Test::~Test()析构函数中,否则i的内存将被泄漏。