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;
}