头文件中的C ++循环依赖 [英] C++ Circular Dependency in Header Files

查看:116
本文介绍了头文件中的C ++循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能避免以下头文件中的循环依赖而无需 A类中的数据成员 b1 转向指针/引用,并放宽 B类中的内联功能要求?



Ah:

  #ifndef A_H 
#define A_H
#include< B.h> //必需,因为数据成员b1不是指针/引用

类A {
public:
B b1; //我想保持原样。
int m_a;
};

#endif

Bh:

  #ifndef B_H 
#定义B_H
#include< A.h> //是必需的,因为f()调用了A类的成员函数

B类{
public:
int f(A& a){返回a.m_a; } //我希望这是一个内联函数。
};

#endif

...而让我们说main.ccp是:

  #include< iostream> 
#include< A.h>
#include< B.h>

int main(){
A a;
B b;

std :: cout<< 调用b.f(a):<< b.f(a)<< std :: endl;

返回0;
}


解决方案

您可以使用: / p>

Ah

  #include< B.h> 
#ifndef A_H
#定义A_H

A类
{
public:
B b1;
int m_a;
};

#endif // A_H

Bh

  #ifndef B_H 
#定义B_H

A类;

B类
{
public:
int f(A& a);
};

#include< A.h>

inline B :: f(A& a)
{
return a.m_a;
}

#endif // B_H

main.cpp

  #include< iostream> 
#include< A.h> //这些顺序可以是任意顺序
#include< B.h>

int main()
{
A a;
B b;

std :: cout<< 调用b.f(a):<< b.f(a)<< std :: endl;

返回0;
}


Is it possible to avoid circular dependency in the following header files without turning data member b1 in class A to a pointer/reference, and without relaxing the inline function requirement in class B?

A.h:

#ifndef A_H
#define A_H
#include <B.h> // Required, as data member b1 is not a pointer/reference

class A {
    public:
        B b1; // I want to keep this as as it is.
        int m_a;
};

#endif

B.h:

#ifndef B_H
#define B_H
#include <A.h> // Required, as f() calls a member function of class A

class B {
    public:
       int f(A &a){return a.m_a;} // I want this to be an inline function.
};

#endif

...and let's say main.ccp is:

#include <iostream>
#include <A.h>
#include <B.h>

int main() {
    A a;
    B b;

    std::cout << "Calling b.f(a): " << b.f(a) << std::endl;

    return 0;
}

解决方案

You could use this:

A.h

#include <B.h>
#ifndef A_H
#define A_H

class A 
{
public:
    B b1;
    int m_a;
};

#endif // A_H

B.h

#ifndef B_H
#define B_H

class A;

class B 
{
public:
    int f(A &a);
};

#include <A.h>

inline int B::f(A &a)
{
    return a.m_a;
}

#endif // B_H

main.cpp

#include <iostream>
#include <A.h> // these could be in any order
#include <B.h>

int main() 
{
    A a;
    B b;

    std::cout << "Calling b.f(a): " << b.f(a) << std::endl;

    return 0;
}

这篇关于头文件中的C ++循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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