命名空间namespace

本文介绍了C++中如何通过命名空间组织类,包括如何在类定义、main函数和函数内部声明和使用命名空间。实例展示了如何避免命名冲突,并强调了命名空间在大型项目中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.将类放在命名空间

#include <stdio.h>
#include <stdlib.h>
//将类定义在命名空间中
namespace Diy{
	class Student{
	public:
		char *name;
		int age;
		float score;

	public:
		void say(){
			printf("%s的年龄是%d,成绩是%f\n", name, age, score);
		}
	};
}

int main(){
	Diy::Student stu1;
	stu1.name = "小明";
	stu1.age = 15;
	stu1.score = 92.5f;
	stu1.say();
	system("pause");
	return 0;
}

2.在main函数中声明命名空间

#include<iostream>
#include<string>
#include<stdlib.h>
//声明命名空间std

int main(){
	using namespace std;
	//定义字符串变量
	string str;
	//定义int定义
	int age;
	//从控制台获取用户输入
	cin >> str >> age;
	//将数据输出到控制台
	cout << str << "已经成立" << age << "年了!" << endl;
	system("pause");
	return 0;
}

3.在fun函数中声明命名空间

#include <iostream>
#include <stdlib.h>
void func(){
	//必须重新声明
	using namespace std;
	cout << "msdn" << endl;
}

int main(){
	//声明命名空间std
	using namespace std;
	cout << "csdn" << endl;
	func();
	system("pause");
	return 0;
}

4.在所有函数中都使用命名空间

#include <iostream>
#include <stdlib.h>
//声明命名空间std
using namespace std;

void func(){
	cout << "csdn" << endl;
}

int main(){
	cout << "msdn" << endl;
	func();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值