C++入门(一)

目录

命名空间:

为什么要提出命名空间?

命名空间的定义:

命名空间的使用:

加命名空间名称及作用域限定符:

使用using将命名空间中某个成员引入:

使用using namespace命名空间名称引用:

C++输入&输出:

库的导入:

使用说明:

输入和输出:

输入流:

输出流:

缺省参数:

缺省参数的概念:

缺省参数的分类:

全缺省参数:

半缺省参数:

命名空间:

为什么要提出命名空间?

#include <stdio.h>
#include <stdlib.h>
    int rand = 0;
int main()
{
	printf("%d\n", rand);
	return 0;
}

输出结果:

由于cpp中包含的stdlib库中有rand变量,这个变量的名称存在于全局作用域当中,可能会与cpp文件中定义的变量发生冲突,所以需要一种方式区分这两个变量,这时就需要命名空间规划命名空间域,对标识符名称进行本地化,以免命名冲突,从而解决这个问题。

命名空间的定义:

namespace code
{
	int rand = 0;
}

定义命名空间需要使用namespace关键字,后面跟着·命名空间的名字,然后一对{}将想要命名的成员包起来

//命名空间内部还可以包含函数和结构体
namespace code
{
	int rand = 0;

	int Add(int x, int y)
	{
		return x + y;
	}

	struct Node
	{
		struct Node* next;
		int val;
	};
}

//命名空间还可以嵌套设计
namespace code1
{
    int rand1 = 0;
namespace code 2
{
    int rand2 = 0;
}
}

命名空间的使用:

加命名空间名称及作用域限定符:

#include <stdio.h>
#include <stdlib.h>
namespace code
{
	int rand1 = 0;
	int rand2 = 0;
}

int main()
{
	printf("%d\n", code::rand1);
	return 0;
}

使用using将命名空间中某个成员引入:

#include <stdio.h>
#include <stdlib.h>
namespace code
{
	int rand1 = 0;
	int rand2 = 0;

}
using code::rand1;
int main()
{
	printf("%d\n", rand1);
	return 0;
}

使用using namespace命名空间名称引用:

#include <stdio.h>
#include <stdlib.h>
namespace code
{
	int rand1 = 0;
	int rand2 = 0;

}
using namespace code;
int main()
{
	printf("%d\n", rand1);
	return 0;
}

C++输入&输出:

库的导入:

#include <iostream>
using namespace std;

iostream是cpp内部的库,std是cpp标准库的命名空间名,cpp将标准库的定义和实现都放到了这个命名空间中,这里需要使用std命名空间内部包含的变量和关键字,所以需要将std命名空间展开

使用说明:

这里的输入和输出要使用iostream头文件包含的std命名空间内的关键字:

cout和endl控制输入操作,其中cout是全全局对象流,endl是特殊的cpp符号,表示换行输出;cout与<<配合使用,向控制台输出对象,功能类似于C语言中的printf

cin是全局流对象,搭配>>配合使用,由键盘输入到控制流当中,功能类似于C语言中的scanf

输入和输出:

输入流:

#include <iostream>
using namespace std;

int  main()
{
	cout << "hello world" << endl;
	return 0;
}

输出结果:

输出流:

#include <iostream>
using namespace std;

int  main()
{
	int a = 0;
	cin >> a;
	cout << a << endl;
	return 0;
}

输出结果:


缺省参数:

缺省参数的概念:

缺省参数是声明或定义函数时为函数指定一个缺省值,在调用该函数时,如果没有指定实参则·采取该形参的缺省值,否则使用指定的实参

#include <iostream>
using namespace std;
void Node(int a = 0)
{
	cout << a << endl;
}

int  main()
{
	Node();
	Node(10);
}

缺省参数的分类:

全缺省参数:

void Node(int a = 1,int b = 2,int c = 3)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}

半缺省参数:

void Node(int a ,int b = 2,int c = 3)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}

  • 38
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值