当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++命名空间和引用(代码教程)

c++命名空间和引用(代码教程)

2018年09月13日  | 移动技术网IT编程  | 我要评论

北京ume,触手控图片,天海翼作品番号

< >c++命名空间和引用(代码教程)
#include 
//c++中的输入输出头文件
#include 


//标准命名空间包含了许多标准的订义
using namespace std;
//命名空间类似于java中的包
/*
//自定义命名空间
namespace nsp_a{
 int a = 10;
}

namespace nsp_b{
 int b = 30;
}

//命名空间嵌套结构体
namespace nsp_c{
 int a = 40;
 struct teacher{
  char* name;
  int age;
 };
 struct student{
  char* name;
  int age;
 };
}
//命名空间中嵌套命名空间
namespace nsp_d{
 namespace nsp_inner_d{
  int d = 80;
 }
}

void main(){
 //std::cout << "hello world" << std::endl;
 cout << "hello world" << endl;

 //使用命名空间,::代表修饰符
 cout << nsp_a::a << endl;
 cout << nsp_b::b << endl;

 //使用命名空间中嵌套的结构体
 struct nsp_c::teacher t;
 t.name = "tom";
 cout << t.name << endl;

 using nsp_c::teacher;
 teacher t1;
 t1.name = "jack";
 cout << t1.name << endl;

 //使用命名空间中嵌套的命名空间
 cout << nsp_d::nsp_inner_d::d << endl;
 system("pause");
 }*/
//c++中多了class类
/*#define pi 3.14

class circle{
private:
 double r;
 double s;
public:
 void radius(double r){
  this->r = r;
 }
 double gets(){
  return pi*r*r;
 }
};

void main(){
 //类的使用
 circle c;
 c.radius(4);//函数
 cout << c.gets() << endl;

 system("pause");
}*/
//c++中的结构体进行了加强
/*struct teacher{
public:
 char* name;
 int age;
public:
 void say(){
  cout << "age"<
//布尔类型,c++中有bool类型
/*
void main(){
 //bool issingle = true;
 bool issingle = 17;
 //false -17

 if (issingle){
  cout << "单身" << endl;
  cout << sizeof(bool) << endl;
 }
 else{
  cout << "有对象" << endl;
 }

 int a = 10, b = 20;
 ((a > b) ? a : b) = 30;
 cout << b << endl;
 system("pause");
}*/
//引用 c++中有引用,也叫别名
/*void main(){
 //变量名-门牌号(内存空间0x00001的别名,可不可以有多个名字?)
 int a = 10;
 //b就是这个内存空间的别名,也就是b叫0x0001
 //& 在c++中叫引用
 int &b = a;
 cout << b << endl;
 system("pause");
}*/
void swap(int* a, int* b){
 int c = 0;
 c = *a;
 *a = *b;
 *b = c;
}

void swap2(int &a, int &b){
 int c = 0;
 c = a;
 a = b;
 b = c;
}

void main(){
 int x = 10;
 int y = 20;
 //交换前
 cout << x << "和" << y << endl;
 //通过指针交换两个数
 swap(&x, &y);
 cout << x << "和" << y << endl;
 //通过别名,引用交换两个数
 swap(x, y);
 cout << x << "和" << y << endl;
 system("pause");
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网