【问题标题】:Missing definition error is solved by including only a declaration通过仅包含声明来解决缺少定义错误
【发布时间】:2016-04-16 18:20:24
【问题描述】:

为什么包含声明可以解决缺少定义的错误?这与an earlier question 有关。

在以下一组文件中,我很惊讶地为未使用的类寻找定义,然后当我只包含程序编译的类的声明时。

我已经为必须添加的包含添加了 cmets,但不明白为什么在那些特定的 .cpp 文件中需要它们。

啊.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;
}

【问题讨论】:

    标签: c++


    【解决方案1】:
    1. B 在 C.cpp 中使用。用于C的成员变量的定义中。

    2. B.hpp 不包含 B 类的声明(应该是class B;)。它包含它的定义(但不包含它的成员)。

    【讨论】:

      【解决方案2】:

      STL 容器中不允许使用不完整类型(前向声明),即使 boost 容器允许这样做。我认为如果您包含所需的头文件而不是前向声明,它将解决此问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多