c++ - 前向声明与包含

标签 c++ class forward-declaration

考虑以下两种情况(编辑只是为了完成整个问题并使其更清晰)

案例 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 起作用。

最佳答案

前向声明不能替代包含头文件。

顾名思义,前向声明只是一个声明 而不是定义

因此,您将声明编译器说它是一个类,而我只是在这里声明它,并会在何时使用它时为您提供定义。因此,通常您在 Header 文件中 forward declare 并在 .cpp 文件中 #include 您将在其中 使用 前向声明类的成员.

通过这样做,你所做的是,无论你在哪里包含头文件,都会有一个类的声明,而不是整个内容#included...

不过话说回来,当编译器需要类的定义时,应该是#included..

因此,在您的情况下, A obj; 需要 class A 的定义,因此您应该 #include..

我自己也问过类似的问题 here和另一个 similar question这也有一个很好的答案......

希望对你有帮助..

关于c++ - 前向声明与包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3632818/

相关文章:

c++ - 使用 Chromium (CEF 3) 时 CoInitializeSecurity 无法成功

Java Greenfoot,无法在文件之间链接方法

python - 使用类将整数列出为字符串

c++ - C++/类中相互依赖的循环依赖

c++ - 是否应该从命名空间库中向前声明类?

c++ - CMake:使用 OBJECT 库功能创建的 Visual Studio 项目

c++ - 将 protected 析构函数虚拟化是否有用?

c++ - 为什么仅当输入为 5 时才会出现运行时错误?

java - 接口(interface)是 Java 8 中实用程序类的有效替代品吗?

typescript - typescript 中的前向声明