C++面向对象

C++面向对象,第1张

C++ Header Guards
    • Description:
    • 例一:定义同名函数
    • 例二:重复调用头文件
    • 防卫式声明:

Description:

C++ 中的条件 Header Guards(防卫式声明)是条件编译指令,有助于避免由于程序员的错误多次定义相同的函数或变量时出现的错误。 根据 C++,当一个函数或一个变量被多次定义时,它会产生一个错误。

例一:定义同名函数

代码:

#include 
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

// 	C++ program to create fruit class
// file named as "fruit.h"
#include 
#include 
using namespace std;

// Fruit Class
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

// 	C++ program
// file named as "apple.h"
#include 
#include 
#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

// 	C++ program
// file named as "main.cpp"
# include "fruit.h"
# include "apple.h"
# include 
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

// 	C++ program to create fruit class
// file named as "fruit.h"
#ifndef _FRUIT_
#define _FRUIT_

#include 
#include 
using namespace std;

// Fruit Class
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

// 	C++ program
// file named as "apple.h"
#ifndef _APPLE_
#define _APPLE_

#include 
#include 
#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

// 	C++ program
// file named as "main.cpp"
# include "fruit.h"
# include "apple.h"
# include 
using namespace std;

int main() {

	apple a;

	a.apple_input();
	a.apple_display();
	
	return 0;
}

Output:

apple color is red

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/797523.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存