1、用预编译指令符可以避免在多文件工程中调用文件的时候可能出现的重复定义的现象。

比如:

Main.cpp

#include “Animal.h”

#include “Fish.h”

……

 

Animal.h

class Animal()

{

                  

}

 

Fish.h

#include “Animal.h”

class Fish():public Animal

{

        

}

 

因此在调用Main.cpp的时候先运行

1#include “Animal.h”      复制Animal.h过来

class Animal()

{

                           

}

 

2#include “Fish.h” 复制Fish.h过来

#include “Animal.h”     复制Animal.h过来

class Animal()

{

                                    

}

 

class Fish():public Animal

{

                  

}

 

……

因此最后的文件应该是形如:

class Animal()

{

                           

}

class Animal()

{

                           

}

class Fish():public Animal

{

                  

}

因此重复定义了类

class Animal()

{

                           

}

是显而易见的。

这时候引入预编译指令符的方法来避免这样的现象来发生。

假设在最后的文件中我们来补充预编译指令符的方法:

 

                   #ifndef      ABCD       //如果没有定义ABCD,否则转向endif

                   #define      ABCD       //那么就定义ABCD

class Animal()

{

                           

}

#endif

 

#ifndef      ABCD       //如果没有定义ABCD,否则转向endif

                   #define      ABCD       //那么就定义ABCD

class Animal()

{

                           

}

#endif

 

class Fish():public Animal

{

                  

}

添加蓝色部分就可以避免重复定义了。

因此可以在多文本文件中做如下修改:

Main.cpp

#include “Animal.h”

#include “Fish.h”

……

 

Animal.h

#ifndef      ABCD       //如果没有定义ABCD,否则转向endif

#define      ABCD       //那么就定义ABCD

class Animal()

{

                  

}

#endif

 

Fish.h

#include “Animal.h”

#ifndef      ABCD       //如果没有定义ABCD,否则转向endif

#define      ABCD       //那么就定义ABCD

class Fish():public Animal

{

        

}

#endif

这样当Main.cpp在编译的时候就会忽略重复的定义而避免错误的产生了。

相关文章:

  • 2021-06-24
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-21
  • 2022-12-23
  • 2021-08-14
  • 2021-07-26
相关资源
相似解决方案