C++面向对象(1):防卫式声明

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

// 	C++ program to create fruit class
// file named as "fruit.h"
#include <iostream>
#include <cstring>
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 <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

// 	C++ program
// file named as "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

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

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

// 	C++ program
// file named as "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
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值