为什么C++的头文件需要做防卫式声明?

2020-03-30  本文已影响0人  哈煌

防止同一个头文件被包含多次而导致重复定义。

举个例子:如果没有防卫式声明

// 头文件 A.h

class A{};

// 头文件 B.h

#include "A"

using namespace std;

class B{};

// main.cpp

#include "A"

#include "B"

using namespace std;

int main()

{

    B b;

    reutrn 0;

}

编译出错,Redefination of 'A'

为什么会出现这样的情况??

在编译阶段,编译器会把头文件展开。此时main.cpp中的代码如下:

class A{};

calss A{};

class B{};

int main()

{

    B b;

    return 0;

}

上一篇 下一篇

猜你喜欢

热点阅读