【问题标题】:How to handle inter-dependency/ circular dependency in Visual Studio(C++11)如何在 Visual Studio(C++11) 中处理相互依赖/循环依赖
【发布时间】:2018-10-19 02:52:19
【问题描述】:

我正在尝试为两个相互依赖的类创建头文件和类文件。我尝试使用#pragma onceextern 类声明,在彼此的标题中声明类。它们似乎都不起作用。这是我的示例代码:

啊.h

#pragma once
#include "B.h"

class A
{
    private:
        int num;
    public:
        A();
        void printB(B b);
        int getA();
        ~A();
};

A.cpp

#pragma once
#include "stdafx.h"
#include "A.h"
#include <iostream>


A::A()
{
    num = 5;
}

void A::printB(B b)
{
    std::cout << "b = " << b.getB()  << std::endl;
}

int A::getA()
{
    return num;
}

A::~A()
{
}

B.h

#pragma once
#include "A.h"
class B
{
    private:
        char ch;
    public:
        B();
        void printA(A a);
        char getB();
        ~B();
};

B.cpp

#pragma once
#include "stdafx.h"
#include <iostream>
#include "B.h"


B::B()
{
    ch = 'g';
}

void B::printA(A a)
{
    std::cout << "a = " << a.getA() << std::endl;
}

char B::getB()
{
    return ch;
}

B::~B()
{
}

Interedependency.cpp [入口点/主文件]

#pragma once
#include "stdafx.h"
#include "A.h"


int main()
{
    A a;
    B b;
    a.printB(b);
    b.printA(a);
    return 0;
}

在 Visual Studio 中如何处理这种相互依赖的类?

【问题讨论】:

  • 我认为您应该着眼于向前声明一个类,而不是包括标题,例如B类;类 A { ... };然后在 a.cpp 中包含“b.h”
  • 这与visual studio无关,这是一个C++问题(甚至不是c++11)。
  • #pragma once 仅对 header 有用(不包括 cpp 文件)。

标签: c++ class circular-dependency


【解决方案1】:

不要在标题中包含A.hB.h,而是在B.hA.h 中转发声明AB
在您的 cpp 文件中,包括来自B.cppA.h 和来自A.cppB.h

A.h - 将#include "B.h" 替换为class A; - 这告诉编译器我们将使用A 类,但我们稍后会提供详细信息。
编译器此时只关心类大小(在您的情况下)。
在 cpp 文件中,包含 B.h 以实际告诉编译器 B 是什么,因为您将实际使用它。
B.hB.cpp 执行相同操作 - 将包含替换为标头中的前向声明,并在源文件中包含另一个标头。

另外,cpp 文件中不需要#pragma once,它们已经编译过一次。

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2011-09-18
    • 2013-03-18
    • 1970-01-01
    • 2011-07-26
    • 2014-08-02
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多