A - > B,B - A类关联 [英] A -> B, B -> A classes association

查看:142
本文介绍了A - > B,B - A类关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码没有什么特别的。它只是一个片段来显示前向声明的问题。只是一个简单的问题:为什么它不工作,如何强制它工作?

This code doesn't do anything special. It's just a snippet to show the problem with forward declarations. Just a short question: why doesn't it work and how to force it to work?

class A;

class B {
    A obj;
public:
    int getB() const {
        return 0;
    }
    void doSmth() {
        int a = obj.getA();
    }
};

class A {
    B obj;
public:
    int getA() const {
        return 1;
    }
    void doSomething() {
        int b = obj.getB();
    }
};

此代码给出错误:

error C2079: 'B::obj' uses undefined class 'A'
error C2228: left of '.getA' must have class/struct/union


推荐答案

这种类型的循环依赖在C ++中是不可能的。您不能使对象包含对方。然而,您可以存储指针或引用。你也不能真正使用没有完整定义的类的方法。

That type of circular dependency is not possible in C++. You can't have objects containing each other. You can however store pointers or references. You also can't really use a method of a class without the full definition.

所以,你需要做两件事:

So, there's two things you need to do:

1)用指针替换对象。

1) Replace the objects with pointers.

2)在类定义之后实现方法。如果这些都在标题中,您需要将它们标记为 inline 以防止多个定义。

2) Implement the method after the class definitions. If these are in a header, you'll need to mark them as inline to prevent multiple definitions.

class A;
class B {
    std::shared_ptr<A> obj;
public:
    int getB() const;
    void doSmth();
};

class A {
    std::shared_ptr<B> obj;
public:
    int getA() const;
    void doSomething();
};


inline int B::getB() const {
        return 0;
    }
inline void B::doSmth() {
        int a = obj->getA();
    }


inline int A::getA() const {
        return 1;
    }
inline void A::doSomething() {
        int b = obj->getB();
    }

这篇关于A - &gt; B,B - A类关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆