c++ 类相互引用

2021/10/26 11:10:20

本文主要是介绍c++ 类相互引用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

类A和类B相互引用

文件 A.h

#ifndef HEAD_A
#define HEAD_A
​
#include"B.h"
class B;
​
class A
{
private:
    /* data */
​
public:
    A(/* args */);
    ~A();
​
    B* b;
    const char* sayYes();
};
​
​
#endif

文件 A.cpp

​
#include"A.h"
​
A::A(/* args */)
{
}
​
A::~A()
{
}
​
const char* A::sayYes()
{
    return "A:yes.";
}

文件 B.h

​
#ifndef HEAD_B
#define HEAD_B
​
#include"A.h"
// #include"A.cpp"
class A;
​
class B
{
private:
    /* data */
    int i;
public:
    B(/* args */);
    ~B();
​
    const char* sayYes();
    A* a;
};
#endif

文件 B.cpp

​
#include"B.h"
​
​
​
B::B(/* args */)
{
}
​
B::~B()
{
}
​
const char* B::sayYes(){return "B:yes.";}

文件 main.cpp

#include <iostream>
using namespace std;
​
#include "A.h"
#include "A.cpp"
​
#include "B.h"
#include "B.cpp"
​
int main()
{
    A a;
    B b;
​
    cout << "hello world  1  :" << a.sayYes() << endl;
    cout << "hello world  2  :" << a.b->sayYes() << endl;
​
    cout << "hello world  3  :" << b.sayYes() << endl;
    cout << "hello world  4  :" << b.a->sayYes() << endl;
}

== end



这篇关于c++ 类相互引用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程