Description:
C++ 中的条件 Header Guards(防卫式声明)是条件编译指令,有助于避免由于程序员的错误多次定义相同的函数或变量时出现的错误。 根据 C++,当一个函数或一个变量被多次定义时,它会产生一个错误。
例一:定义同名函数
代码:
#include <iostream>
using namespace std;
void complex() {
cout<<"this number is complex number!"<<endl;
return;
}
void complex() {
cout<<"this number is also complex number!"<<endl;
return;
}
int main() {
complex();
return 0;
}
Output:
E:\TSWorld程序\complex.cpp:10:6: error: 'void complex()' previously defined here
分析: 定义了两个同名函数,所以会报错。
例二:重复调用头文件
Program 1:fruit.h
#include <iostream>
#include <cstring>
using namespace std;
class Fruit {
string name;
string color;
public:
void input() {
name = "apple";
color = "red";
}
void display() {
cout<< name <<" color is " << color <<endl;
}
};
Program 2: apple.h
#include <iostream>
#include <cstring>
#include "fruit.h"
using namespace std;
class apple {
Fruit a;
public:
void apple_input() {
a.input();
}
void apple_display() {
a.display();
}
};
Program 3: main.cpp
# include "fruit.h"
# include "apple.h"
# include <iostream>
using namespace std;
int main() {
apple a;
a.apple_input();
a.apple_display();
return 0;
}
Output:
In file included from E:\TSWorld程序\main.cpp:3:0:
E:\TSWorld程序\fruit.h:10:7: error: previous definition of 'class Fruit'
class Fruit {
分析: main.cpp 和 apple.h 都调用的 fruit.h,重复调用了头文件。
防卫式声明:
Program 1:fruit.h
#ifndef _FRUIT_
#define _FRUIT_
#include <iostream>
#include <cstring>
using namespace std;
class Fruit {
string name;
string color;
public:
void input() {
name = "apple";
color = "red";
}
void display() {
cout<< name <<" color is " << color <<endl;
}
};
#endif
Program 2: apple.h
#ifndef _APPLE_
#define _APPLE_
#include <iostream>
#include <cstring>
#include "fruit.h"
using namespace std;
class apple {
Fruit a;
public:
void apple_input() {
a.input();
}
void apple_display() {
a.display();
}
};
#endif
Program 3: main.cpp
# include "fruit.h"
# include "apple.h"
# include <iostream>
using namespace std;
int main() {
apple a;
a.apple_input();
a.apple_display();
return 0;
}
Output:
apple color is red
|