考虑以下两种情况(编辑只是为了完成整个问题并使其更清晰)
案例1:(没有按照下面正确的方式编译)
//B.h
#ifndef B_H
#define B_H
#include "B.h"
class A;
class B {
A obj;
public:
void printA_thruB();
};
#endif
//B.cpp
#include "B.h"
#include <iostream>
void B::printA_thruB(){
obj.printA();
}
//A.h;
#ifndef A_H
#define A_H
#include "A.h"
class A {
int a;
public:
A();
void printA();
};
#endif
//A.cpp
#include "A.h"
#include <iostream>
A::A(){
a=10;
}
void A::printA()
{
std::cout<<"A:"<<a<<std::endl;
}
//main.cpp
#include "B.h"
#include<iostream>
using namespace std;
int main()
{
B obj;
obj.printA_thruB();
}
案例2:(唯一的修改......没有编译错误)
//B.h
#include "A.h" //Add this line
//class A; //comment out this line
让我们假设 A.cpp 和 B.cpp 一起编译。以上两种情况有什么区别吗?是否有理由更喜欢一种方法而不是另一种?
编辑:那么我如何使方案 1 起作用。