c++ circular dependency

董新觉
2023-12-01

A类的成员函数中调用B,B类中成员变量有A

  • 1.hpp
#include <iostream>

namespace test
{
    class A
    {
    public:
        struct C
        {
            int a;
            int b;
            C(int aa=1, int bb=1){
                a = aa;
                b = bb;
            }
            int plus(){
                return a + b;
            }

        };
        void put();
        void pp();
        static  C s;
    };
}
  • 1.cpp
#include <iostream>
#include "2.hpp"

namespace test{
    void A::put(){
        std::cout << "dsada" << std::endl;
    }
    void A::pp(){
        B u;
        u.qq();
    };
}
  • 2.hpp
#include <iostream>
#include "1.hpp"
namespace test
{
    class B
    {
    public:
        void put();
        void qq();
    private:
        A i;
    };
}
  • 2.cpp
#include <iostream>
#include "2.hpp"
namespace  test{
    void B::put(){
        i.put();
    }
    void B::qq(){
        std::cout << "dasdasd" << std::endl;
    };
}
  • main.cpp
#include "2.hpp"
#include "1.hpp"
#include <iostream>
int main()
{
    test::A i;
    i.put();
    i.pp();
    test::A::C a;
//    test::A::C &k = test::A::s;
    std::cout << a.plus() << std::endl;
    return 0;
}

circular dependency

  • 主要是因为两个文件的头文件相互引用,导致了循环编译,才会出错。
  • 为了避免循环编译,可以将类的定义和声明拆分,如果两个类都为各自的成员变量,其中一个需要声明类,具体如下:
  • 1.hpp
#include <iostream>

namespace test
{
    class B;
    class A
    {
    public:
        void put();
        void pp();
        B * k;
    };
}
  • 1.cpp
#include <iostream>
#include "2.hpp"

namespace test{
    void A::put(){
        k->qq();
    }
    void A::pp(){
        B u;
        u.qq();
    };
}
  • 2.hpp
#include <iostream>
#include "1.hpp"
namespace test
{
    class B
    {
    public:
        void put();
        void qq();
    private:
        A i;
    };
}
  • 2.cpp

#include <iostream>
#include "2.hpp"
namespace  test{
    void B::put(){
        i.put();
    }
    void B::qq(){
        std::cout << "dasdasd" << std::endl;
    };
}
  • main.cpp
#include "2.hpp"
#include "1.hpp"
#include <iostream>
int main()
{
    test::A i;
    i.put();
    i.pp();
    return 0;
}
 类似资料: