C++入门基础知识

一、命名空间namespace

1.命名空间是指标识符的可见范围,C++标准库中的所有标识符都在std的命名空间里。

2.命名空间的使用:

#include <iost>
using namespace std;//命名空间的定义
int main()
{                  //{}为命名空间的作用域
 int a = 0;
 return 0;
}

3.使用标识符限定命名空间

域作用访问符用“::”表示,用来访问命名空间下的标识符。

std::cout << "hello world!" << endl;

二、C++基本的输入输出流

1.输出流对象:

cout是输出流对象,“<<”是插入运算符,与cout配合使用

2.输入流对象:

cin是输入流对象,“>>”是提取运算符,与cin配合使用

#include <iostream>
using namespace std;
int main()
{
	int a;
	cin >> a;
	cout << "a="<<a<<endl;
	return 0;
}

三、重载

1.重载的定义

在C++中,可以将语义、功能相似的几个函数用同一个名字表示,即函数重载。

C++里面允许同名函数存在,但其中的参数列表不能相同。

#include <iostream>
#include <stdlib.h>
using namespace std;

void funcl(int a, int b)
{
	cout << a << endl;
	cout << b << endl;
}
void funcl(int a)
{
	cout << a << endl;
}

int main()
{
	funcl(1, 2);
	funcl(3);
	system("pause");
	return 0;
}


2.为什么需要函数重载?

在C++中,类的构造函数和类名相同,如果没有函数的重载,实例化不同的对象比较麻烦。

3.C语言中没有函数的重载


四、C++缺省函数

1.缺省函数的定义:

缺省函数是在声明函数的某个参数的时候为之指定一个默认值,在调用该函数时如果采用该默认值,就不需要指定该函数。

2.缺省参数的使用规则:

调用时只能从最后一个参数开始省略,即:带缺省值的参数必须放在参数表的最后面。

3.缺省值必须是常量。

具体用法如下:

//缺省函数
#include <iostream>
#include <stdlib.h>
using namespace std;

int Add(int a, int b)
{
	return a + b;
}

int main()
{
	cout << Add(1, 2) << endl;
	system("pause");
	return 0;
}


//全缺省
#include <iostream>
#include <stdlib.h>
using namespace std;

int Add(int a = 1, int b = 2)
{
	return a + b;
}

int main()
{
	cout << Add()<< endl;
	system("pause");
	return 0;
}

//半缺省
#include <iostream>
#include <stdlib.h>
using namespace std;

int Add(int a, int b = 2)
{
	return a + b;
}

int main()
{
	cout << Add(1) << endl;
	system("pause");
	return 0;
}

五、指针和引用

1.引用的概念:

引用就是对某一变量的一个别名。

特点为:(1)一个变量可以取多个别名;

        (2)引用必须初始化;

        (3)只能初始化一次。

2.引用的使用方法:

声明方法:类型标识符&引用名=目标变量名

//引用的使用
#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
	int a = 10;
	int& b = a;
	cout << a << endl;
	cout << b << endl;
	system("pause");
	return 0;
}

3.引用做参数、做返回值的作用:

引用的作用:(1)作参数和返回值

            (2)提高效率

//引用作参数和返回值
#include <iostream>
#include <stdlib.h>
using namespace std;

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

int main()
{
	int x = 1;
	int y = 2;
	cout << x << " " << y << endl;
	Swap(x, y);
	cout << x << " " << y << endl;
	system("pause");
	return 0;
}

4.指针和引用的区别

(1)在语法上,指针是地址,引用时别名;从根本上指针和引用都是地址的概念;

(2)引用只能在定义是被初始化一次,指针可以改变;

(3)引用不能为空,指针可以为空;

(4)指针和引用自增++的意义不同;

(5)程序为指针变量分配内存,而引用不需要分配内存区域。

猜你喜欢

转载自blog.csdn.net/weixin_39294633/article/details/78116890