2016-04-16 5 views
0

宣言を含めると定義エラーが解決されないのはなぜですか?これはan earlier questionに関連しています。宣言のみを含めると、定義エラーが解消されます。

次のファイルセットでは、使用されていないクラスに対して定義が求められていて、プログラムがコンパイルするクラスの宣言のみを含めると驚いています。

私が追加しなければならないインクルードについてのコメントを追加しましたが、それらの特定の.cppファイルに必要な理由が理解できません。

A.h

#ifndef A_h 
#define A_h 

#include <map> 

class C; 

class A { 
public: 
    C& add(); 
    std::map<int,C> Cmap; 
    void dosomethingwithC(); 
}; 

#endif 

B.h

#ifndef B_h 
#define B_h 

#include <map> 

class A; 

class B { 
public: 
    A& add(); 
    std::map<int,A> Amap; 
}; 

#endif 

C.h

#ifndef C_h 
#define C_h 

#include <map> 

class B; 

class C { 
public: 
    B& add(); 
    std::map<int,B> Bmap; 
}; 

#endif 

A.cpp

#include "A.h" 

#include "B.h"// Required here, but B isn't used in this file. 
       // Without B.h the error is 
       // error C2079: 'std::pair<const _Kty,_Ty>::second' uses undefined class 'B' 
       // But B.h only includes the declaration, not the definition 

#include "C.h" 

C& A::add() 
{ 
    auto emplace_results = Cmap.emplace(std::piecewise_construct, 
     std::forward_as_tuple(3), 
     std::forward_as_tuple()); 
    auto pair_iterator = emplace_results.first; 
    auto& emplaced_pair = *pair_iterator; 
    auto& map_value = emplaced_pair.second; 
    return map_value; 
} 


void A::dosomethingwithC() 
{ 
    Cmap[3].add(); 
} 

B.cpp

#include "A.h" 
#include "B.h" 
#include "C.h" // also required here 

A& B::add() 
{ 
    auto emplace_results = Amap.emplace(std::piecewise_construct, 
     std::forward_as_tuple(3), 
     std::forward_as_tuple()); 
    auto pair_iterator = emplace_results.first; 
    auto& emplaced_pair = *pair_iterator; 
    auto& map_value = emplaced_pair.second; 
    return map_value;; 
} 

C.cpp

#include "A.h" // also required here 
#include "B.h" 
#include "C.h" 

B& C::add() 
{ 
    auto emplace_results = Bmap.emplace(std::piecewise_construct, 
     std::forward_as_tuple(3), 
     std::forward_as_tuple()); 
    auto pair_iterator = emplace_results.first; 
    //auto& emplaced_pair = *pair_iterator; 
    std::pair<const int,B>& emplaced_pair = *pair_iterator; 
    auto& map_value = emplaced_pair.second; 
    return map_value; 
} 

MAIN.CPP

#include "A.h" 
#include "B.h" 
#include "C.h" 

int main() 
{ 
    C c; 
    auto& emplacedB = c.add(); 
    auto& emplacedA = emplacedB.add(); 
    auto& emplacedC = emplacedA.add(); 
    emplacedC.add(); 
    return 0; 
} 

答えて

2
  1. B がC.cppに使用あります。これはB.hppは(class B;であろう)、クラスBの宣言が含まないC.

    のメンバ変数
  2. の定義に使用されます。それにはの定義が含まれています(メンバーではありません)。

0

ブーストコンテナであっても、不完全な型(前方宣言)はSTLコンテナでは許可されません。私は前方宣言の代わりに必要なヘッダーファイルを含める場合、この問題を修正すると思います。

関連する問題