简体   繁体   English

如何互相学习

[英]How to make classes using each other

class A;
class B;

class A
{   
public:
    A(B * b) : b(b)
    {   
        b->foo(this);
    }   
private:
    B * b;
};  

class B
{   
public:
    void foo(A *)
    {}  
};

Compiling this code gives me 编译这段代码给了我

incomplete-type.hpp: In constructor ‘A::A(B*)’:
incomplete-type.hpp:9:4: error: invalid use of incomplete type ‘class B’
   b->foo(this);
    ^~

But I really need the classes to use each other via pointers. 但是我确实需要这些类通过指针相互使用。 How can I do this? 我怎样才能做到这一点?

Move the function definitions that actually use the other type to below, where both types are complete. 将实际使用其他类型的函数定义移到下面,这两种类型均已完成。

class A;
class B;

class A
{   
public:
    A(B * b);
private:
    B * b;
};  

class B
{   
public:
    void foo(A *)
    {}  
};

inline A::A(B * b) : b(b)
{
    b->foo(this);
}

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

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