2015-10-27 104 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的內存將被泄漏。