2013-08-07 64 views
0

我有一些包含三個類的代碼。 相關類結構包括以下:當訪問嵌套類中的空映射時訪問衝突

  • 的Class1包含一個指向的Class2的實例
  • Class2中包含專用CLASS3類和函數以訪問類的引用3
  • CLASS3含有私人地圖類和函數來檢查,如果該映射爲空

我遇到的問題是,當我設置此類似,所以我得到一個訪問衝突:

bool result = class1->class2->GetProperties().CheckEmpty(); 

但如果我把它這樣我沒有任何錯誤:

bool result = class2->GetProperties().CheckEmpty(); 

爲什麼會加入其他類層突然產生這個問題?

這是我用來重現錯誤的代碼。 主線中的兩條線不會產生錯誤,但可以對其中的兩條線進行註釋並取消註釋,並且您將看到錯誤。

#include "stdafx.h" 
#include <map> 

class PropertySet 
{ 
    public: 
     PropertySet::PropertySet(){}; 
     PropertySet::~PropertySet(){}; 

     bool CheckEmpty() const { return properties.empty(); } 

    private: 
     std::map< std::string, std::string > properties; 
}; 

class Tile 
{ 
public: 
    Tile::Tile() {}; 
    Tile::~Tile() {}; 

    // Get a set of properties regarding the tile. 
    const PropertySet &GetProperties() const { return properties; } 

private: 

    PropertySet properties; 
}; 

class Tileset 
{ 
public: 
    Tileset::Tileset(){}; 
    Tileset::~Tileset(){}; 

    Tile* tile; 
}; 

int main() 
{ 
    bool test = false; 

    //NO error----------------------------- 
    Tile* t = new Tile(); 
    test = t->GetProperties().CheckEmpty(); 
    //------------------------------------- 

    //ERROR-------------------------------- 
    //Tileset* t = new Tileset(); 
    //test = t->tile->GetProperties().CheckEmpty(); 
    //------------------------------------- 

    delete t; 

    return 0; 
} 

回答

1

當您構建新的Tileset時,指向Tile的指針未初始化。

Tileset::Tileset(){}; 
Tileset::~Tileset(){}; 

應該

Tileset::Tileset(){ tile = new Tile(); }; 
Tileset::~Tileset(){ delete tile; }; 
+0

感謝您的幫助。我在圖書館遇到了更深層的問題。我試圖縮短代碼量並仍然重現問題,但除非我使用庫,否則它不會發生。 – enr4ged

+0

我猜你正在使用Visual Studio,因爲你有一個stdafx.h包括在內。調試庫可能很煩人,但我通常只是在調用訪問衝突之前設置一個斷點,然後逐行檢查每個指針值以尋找垃圾。訪問衝突很可能是未初始化的指針。 – slaterade