向前宣言与包括 [英] Forward Declaration vs Include
问题描述
请考虑以下两种情况(仅编辑以完成整个问题,并使其更清晰)
案例1 :(不正确编译如下) >
// Bh
#ifndef B_H
#define B_H
#includeBh
A类;
class B {
A obj;
public:
void printA_thruB();
};
#endif
//B.cpp
#includeB.h
#include< iostream>
void B :: printA_thruB(){
obj.printA();
}
//A.h;
#ifndef A_H
#define A_H
#includeA.h
A类{
int a;
public:
A();
void printA();
};
#endif
//A.cpp
#includeA.h
#include< iostream>
A :: A(){
a = 10;
}
void A :: printA()
{
std :: cout<<A:<< a< :endl;
}
//main.cpp
#includeB.h
#include< iostream>
using namespace std;
int main()
{
B obj;
obj.printA_thruB();案例2:(唯一的修改...无需编译错误的工作) / p>
// Bh
#includeAh//添加此行
// A类; //注释掉这一行
让我们假设A.cpp和B.cpp都被一起编译。上述两种情况有什么区别吗?是否有理由比其他方法更喜欢一种方法?
编辑:
那么如何使场景1工作。
解决方案编译B.cpp时,情况1会产生一个不完整类型错误。因为B类包含A类对象,所以A类的定义(特别是大小)需要在B类定义之前完成。
你可以选择使some_variable指向A类的指针或引用,在这种情况下,你的前向声明在Bh中就足够了你仍然需要在B.cpp中的一个完整的定义(假设你实际使用的A成员函数/数据)。
Consider the following two scenarios (Edited just to complete the whole question and make it clearer)
Case 1: (doesnt compile as rightly mentioned below)
//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();
}
Case 2: (the only modifications...works without compiliation error)
//B.h
#include "A.h" //Add this line
//class A; //comment out this line
Let us assume both the A.cpp and B.cpp are complied together. Do the above two scenarios make any differences? Is there a reason to prefer one method over the other?
Edit:
So how do I make scenario 1 work.
解决方案 Case 1 will produce an "incomplete type" error when you compile B.cpp. Because class B contains a class A object, the definition (and in particular the size) of class A is required to be complete before the definition of class B.
Alternatively, you could choose to make some_variable a pointer or reference to class A, and in that case your forward declaration would be sufficient in B.h. You'd still need a full definition of A in B.cpp (assuming you made actual use of the A member functions/data).
这篇关于向前宣言与包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!