我有一對類包括I似乎對於不能避免圓形包括問題:避免圓形與shared_ptrs
point.h
#include group.h // Needed for GroupOfPoints::weak_ptr
class Point
{
private:
double _x;
double _y;
// Groups of points that this point belongs too
std::vector<GroupOfPoints::weak_ptr> _groups;
public:
typedef std::shared_ptr<Point> shared_ptr;
typedef std::weak_ptr<Point> weak_ptr;
Point(); // Constructor
// etc...
}
group.h
#include point.h // Needed for Point::shared_ptr
class GroupOfPoints
{
private:
// Collection of points that fall in this group
std::vector<Point::shared_ptr> _points;
public:
typedef std::shared_ptr<GroupOfPoints> shared_ptr;
typedef std::weak_ptr<GroupOfPoints> weak_ptr;
GroupOfPoints(); // Constructor
// etc...
}
我知道共享和弱指針存在於雙重性中以防止循環所有權,但在指針是成員變量的情況下,我怎樣才能利用這種沒有循環的二元性?必須在頭文件而不是實現文件中定義)?
向前聲明一個類('類Foo;')而不是在其中一個文件中包含頭文件? – HolyBlackCat
'class GroupOfPoints; class Point {std :: vector> _groups; };' –
您必須使用前向聲明[何時可以使用前向聲明?](https://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration) – Rabbid76