首页 / C++ / 第四章 C++编程之命名空间
第四章 C++编程之命名空间
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了第四章 C++编程之命名空间,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2436字,纯文字阅读大概需要4分钟。
内容图文
第四章 C++编程之命名空间
4.1 域运算和命名空间
条件:通过命名空间和域运算的实现
命名空间的好处:解决了不同工程师定义了相同的类名,避免了冲突,例如:
工程师1命名了一个类叫person,而工程师2也定义了一个类person,此时类就会同名,引入命名空间,避免了这种冲突
4.2 命名空间的使用
代码关系梳理:
命名空间A定义了animal类和person类;命名空间P定义了person类
4.3 代码例程
1、在命名空间A定义animal类和person类的头文件
#ifndef __ANIMAL_H__
#define __ANIMAL_H__
#include <stdio.h>
namespace A{
class Animal{
private:
char *name;
int age;
public:
void setName(char *name);
void setAge(int age);
void printInfo(void);
};
class Person{
private:
char *name;
int age;
public:
void setName(char *name);
void setAge(int age);
void printInfo(void);
};
}
#endif
2、在命名空间A实现animal类和person类中的方法
#include "animal.h"
namespace A{
void Animal::setName(char *name)
{
this->name = name;
}
void Animal::setAge(int age)
{
this->age = age;
}
void Animal::printInfo(void)
{
printf("Animal : name is %s,age is %d\n",this->name,this->age);
}
void Person::setName(char *name)
{
this->name = name;
}
void Person::setAge(int age)
{
this->age = age;
}
void Person::printInfo(void)
{
printf("Person is specific animal : name is %s,age is %d\n",this->name,this->age);
}
}
3、在命名空间P定义person类的头文件
#ifndef __PERSON_H__
#define __PERSON_H__
#include <stdio.h>
namespace P{
class Person{
private:
char *name;
int age;
public:
void setName(char *name);
void setAge(int age);
void printInfo(void);
};
}
#endif
4、在命名空间P实现person类中的方法
#include "person.h"
namespace P{
void Person::setName(char *name)
{
this->name = name;
}
void Person::setAge(int age)
{
this->age = age;
}
void Person::printInfo(void)
{
printf("Person : name is %s,age is %d\n",this->name,this->age);
}
}
5、在主函数中使用命名空间和类
#include "person.h"
#include "animal.h"
using namespace A;
using namespace P;
int main(int argc,char**argv)
{
P::Person stu;
A::Animal dog;
stu.setName("mingming");
stu.setAge(20);
stu.printInfo();
dog.setName("xiaogou");
dog.setAge(2);
dog.printInfo();
A::Person child;//命名空间A中的Person类
child.setName("xiaobudian");
child.setAge(0);
child.printInfo();
return 0;
}
6、使用Makefile编译
#生成可执行文件person,依赖于文件 main.c和person.c
# 符号的意义: $@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件
main:main.o person.o animal.o
g++ -o $@ $^
%.o : %.cpp
g++ -c -o $@ $<
clean:
rm -rf *.o main
4.4 总结
使用命名空间的好处是每个工程师都可以定义自己的命名空间,避免了大量的类导致重名的问题
内容总结
以上是互联网集市为您收集整理的第四章 C++编程之命名空间全部内容,希望文章能够帮你解决第四章 C++编程之命名空间所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。