简体   繁体   English

我该如何处理C ++中的循环组合?

[英]How can I deal with cyclic composition in C++?

I'm trying to create a cyclic composition in C++ but I'm dealing with declaration problems. 我正在尝试在C ++中创建循环组合,但正在处理声明问题。 How could I solve them? 我该如何解决?

This is an example, class A contains a vector of B objects, but class B needs A to be declared first because it's needed in its constructor: 这是一个示例,类A包含一个由B个对象组成的向量,但是类B需要首先声明A,因为在其构造函数中需要它:

class A {
private:
    std::vector<B> sons;
public:
    void create_son() {
        B obj(this);
        sons.push_back(obj);
        obj.some_method();
    }
};

class B {
private:
    A* parent;
public:
    B (A* _parent) { parent = _parent; }
    void some_method() {}
};

In class A , you use object of class B , so the complete definition of class B is needed. class A ,使用class B对象,因此需要class B的完整定义。 To solve this, put class B definition above class A . 要解决此问题,请将class B定义放在class A class B之上。 At the same time, in class B you work only with pointer to A, so you don't need the complete definition of class A : declaration is enough there. 同时,在class B您仅使用指向A的指针,因此您不需要class A的完整定义:声明就足够了。

So, add forward declaration of class A above class B definition. 因此,在class B定义上方添加class A class B前向声明。

class A;

class B {
private:
    A* parent;
public:
    B (A* _parent) { parent = _parent; }
    void some_method() {}
};

class A {
private:
    std::vector<B> sons;
public:
    void create_son() {
        B obj(this);
        sons.push_back(obj);
        obj.some_method();
    }
};

You can forward declare pointer types: 您可以转发声明指针类型:

class A;   // sufficient to fully determine B

class B {
private:
    A* parent;
public:
    B (A* _parent) { parent = _parent; }
    void some_method() {}
};

// now we have B defined, we can define A
class A {
private:
    std::vector<B> sons;
public:
    void create_son() {
        B obj(this);
        sons.push_back(obj);
        obj.some_method();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM