成员互相引用和使用的C ++类

时间:2022-03-15 14:01:59

I have 2 c++ classes with members referencing each other. I am calling members of the referenced classes, so I can't use forward declarations, because I get the error "pointer to incomplete class type is not allowed"

我有2个c ++类,成员互相引用。我正在调用引用类的成员,所以我不能使用前向声明,因为我得到错误“不允许指向不完整类类型的指针”

class A {
    B* b;

    void foo() { 
        b->do_something(); 
    }
};

class B {
    A* a;

    void bar() { 
        a->do_something_else(); 
    }
};

Is there any way to get the includes to work here?

有没有办法让包含在这里工作?

There is already a ticket open by a similar name but I can't use the solution there.

已经有一个类似名称的门票,但我不能在那里使用解决方案。

2 个解决方案

#1


Just separate the definitions from the declarations:

只需将定义与声明分开:

class B;
class A {
public:
    void foo();
    void do_something_else(){}
private:
    B* b;
};
class B {
public:
    void bar();
    void do_something(){}
private:
    A* a;
};

//now B has a complete type, so this is fine
void A::foo() {
    b->do_something();
}

//ditto
void B::bar() {
    a->do_something_else();
}

#2


You can use the prototype definitions in a header file. And the logical body in a cpp file.

您可以在头文件中使用原型定义。和cpp文件中的逻辑体。

After doing this you can use the forward declaration in the header( class B, class A)

执行此操作后,您可以在标题中使用前向声明(B类,A类)

Example: @TartanLlama

#1


Just separate the definitions from the declarations:

只需将定义与声明分开:

class B;
class A {
public:
    void foo();
    void do_something_else(){}
private:
    B* b;
};
class B {
public:
    void bar();
    void do_something(){}
private:
    A* a;
};

//now B has a complete type, so this is fine
void A::foo() {
    b->do_something();
}

//ditto
void B::bar() {
    a->do_something_else();
}

#2


You can use the prototype definitions in a header file. And the logical body in a cpp file.

您可以在头文件中使用原型定义。和cpp文件中的逻辑体。

After doing this you can use the forward declaration in the header( class B, class A)

执行此操作后,您可以在标题中使用前向声明(B类,A类)

Example: @TartanLlama