C++命名空间、内联与捕获

命名空间namespace

最常见的命名空间是std,你一定非常熟悉,也就是:

using namespace std;

命名空间的基本格式

注意,要在头文件里面定义!

namespace namespace_name{
   
	data_type function_name(data_type parameter){
   
		data_type result;
		//function content
		return result;
	}
}

自定义的命名空间

我们可以在头文件里面自定义一个命名空间,步骤为:

  1. 创建一个新的头文件,比如"square.h"
  2. 在main.c中引用该头文件:
#include "square.h"//自己定义的.h头文件需要用双引号
  1. 在"square.h"头文件中进行编码
#ifndef SQUARE_H
#define SQUARE_H

namespace square{
   

    int area(int wid,int len){
   
        return wid*len;
    }
    int around(int wid,int len){
   
        return wid*2+len*2;
    }
}

#endif // SQUARE_H
  1. 在main函数中调用该命名空间,具体有两种调用方式

方式一 每次调用都指明命名空间:

#include 
#include "square.h"

using namespace std;

int main()
{
   
    int wid=10;
    int len=5;

    cout << square::area(wid,len) << endl;
    return 0;
}

方式二 在main函数前声明使用的命名空间,适用于小型项目

#include 
#include "square.h"

using 

你可能感兴趣的:(C编程:返璞归真,c++,算法,开发语言)