-1

我有两个班级 A 和 B

A.hpp

#include <vector>
#include <algorithm>
#include "B.hpp"

class A {
public:
  void sortTrans() { std::sort(trans_.begin(), trans_.end(), sortStruct); }
  unsigned int name() { return name_; }
private:
  std::vector<B*> trans_;
  unsigned int name_;
};

B.hpp:

class A;

class B {
  A& source_;
  A& dest_;
  unsigned int choice_;
};

现在我想按选择和名称的值对 trans_ 进行排序,因此我写了

struct sort {
  bool operator()(B* t1, B* t2) {
    if (t1->choice < t2->choice)
        return true;
    if (t1->dest_.name() < t2->dest_.name())
        return true;
    return false;
  }
} sortStruct;

但现在我面临着打破循环依赖的问题。A的定义在A.hpp中,B的定义在B.hpp中。在 B.hpp 中,我使用 A 的前向减速,A 包括 B.hpp。但是我必须在哪里(或如何)放置 sortStruct,因为它使用 A 和 B 的定义。而且我总是得到错误

Wrong usage of forward declaration A

感谢帮助。

4

4 回答 4

1

两个标头都可以使用前向贬值,因为两者都没有真正(需要)依赖于另一个。

A.hpp

#ifndef A_HPP
#define A_HPP
#include <vector>

class B;

class A {
public:
  void sortTrans();
  unsigned name();
private:
  std::vector<B*> trans_;
  unsigned int attr1_;
  unsigned int attr2_;
};
#endif

B.hpp

#ifndef B_HPP
#define B_HPP_
class A;

class B {
  A& source_;
  A& dest_;
  unsigned choice_;
};
#endif

A.cpp

#include "A.hpp"
#include "B.hpp"
#include <algorithm>

// I can't really define this with your B as given ...
struct SortB {
    bool operator()(B *x, B *y) {
        if (x->choice_ < y->choice_)
            return true;
        if (x->dest_.name() < y->dest_.name())
            return true;
        return false;
    }
 };

void A::sortTrans()
{
    std::sort(trans_.begin(), trans_.end(), SortB());
}

请注意,我还没有展示如何访问 B::choice_ 和 B::dest_,因为这是一个设计决策,我没有足够的信息来做出正确的猜测。

您可以将它们公开(在这种情况下B基本上是一个结构),将访问器成员添加到B,或SortB在 B.hpp 中作为朋友前向声明。

于 2012-12-12T12:45:41.857 回答
0

您可以将声明放在operator()B.hpp实现中 - B.cpp(像往常一样)

// B.hpp
class A;

class B {
  A& source_;
  A& dest_;
};

SortB {
  bool operator()(B* a, B* b); // can be implemented in B.cpp
};

没有什么SortB需要知道的class A

// B.cpp
bool SortB::operator()(B* t1, B* t2) {
    if (t1->attr1() < t2->attr1())
        return true;
    if (t1->attr2() < t2->attr2())
        return true;
    return false;
}

代码A.hpp不需要改动太多:

// A.hpp
#include "B.hpp"

class A {
public:
  void sortTrans() { std::sort(trans_.begin(), trans_.end(), SortB()); }
private:
  std::vector<B*> trans_;
  unsigned int attr1_;
  unsigned int attr2_;
};
于 2012-12-12T12:40:00.890 回答
0

如果一个类有引用成员,则需要提供构造函数/复制构造函数。你提供给B了吗

还注意到t1->attr2()<t2->attr2()不正确。它应该是t1->attr1_t2->attr2_

于 2012-12-12T12:40:50.163 回答
0

您的排序功能可能不是您想要的。它可能应该是这样的

if (b1->choice < b2->choice)
    return true;
if (b1->choice == b2->choice && b1->name < b2->name)
    return true;
return false;

If you don't have a == operator for choice you have to use the < operator reversed and negated to accomplish the same functionality

于 2012-12-12T19:03:34.073 回答