0
点赞
收藏
分享

微信扫一扫

C++基础入门——语法详解篇(下)

sullay 2023-04-24 阅读 104

一、缺省参数

1、1 缺省参数的概念

void Func(int a = 0)
{
 cout<<a<<endl;
}
int main()
{
 Func(); // 没有传参时,使用参数的默认值
 Func(10); // 传参时,使用指定的实参
 
 return 0;
}

1、2 缺省参数的分类

1、2、1 全部缺省

void Func(int a = 10, int b = 20, int c = 30)
{
 cout<<"a = "<<a<<endl;
 cout<<"b = "<<b<<endl;
 cout<<"c = "<<c<<endl;
}

1、2、2 半缺省参数

void Func(int a, int b = 10, int c = 20)
{
 cout<<"a = "<<a<<endl;
 cout<<"b = "<<b<<endl;
 cout<<"c = "<<c<<endl;
}

二、引用

2、1 引用的概念

void Test()
{
 int a = 10;
 int& ra = a;//<====定义引用类型
 
 printf("%p\n", &a);
 printf("%p\n", &ra);
}

2、2 引用特征

void TestRef()
{
 int a = 10;
 int b = 20;
 // int& ra; // 该条语句编译时会出错
 int& ra = a;
 int& rra = a;
 rra = b;  //把b的值赋给rra,不是b的别名
 printf("%p %p %p\n", &a, &ra, &rra); 
}

2、3 引用的使用场景

2、3、1 引用做参数

void Swap(int& left, int& right)
{
 int temp = left;
 left = right;
 right = temp;
}
#include <time.h>
struct A{ int a[10000]; };
void TestFunc1(A a){}
void TestFunc2(A& a){}
void TestRefAndValue()
{
 A a;
 // 以值作为函数参数
 size_t begin1 = clock();
 for (size_t i = 0; i < 10000; ++i)
 TestFunc1(a);
 size_t end1 = clock();
 // 以引用作为函数参数
 size_t begin2 = clock();
 for (size_t i = 0; i < 10000; ++i)
 TestFunc2(a);
 size_t end2 = clock();
 // 分别计算两个函数运行结束后的时间
 cout << "TestFunc1(A)-time:" << end1 - begin1 << endl;
 cout << "TestFunc2(A&)-time:" << end2 - begin2 << endl;
}

 2、3、2 常引用

2、3、3 引用做返回值

 2、4 引用总结

三、内联函数

3、1 内联函数的引出

3、2 内联函数详解

3、2、1 内联函数的概念

3、2、2 内联函数的特性

四、auto关键字(C++11)

4、1 auto简介

#include<iostream>

using namespace std;

int TestAuto()
{
	return 10;
}

int main()
{
	int a = 10;
	auto b = a;
	auto c = 'a';
	auto d = TestAuto();

	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl;
	cout << typeid(d).name() << endl;

	//auto e; 无法通过编译,使用auto定义变量时必须对其进行初始化
	return 0;
}
#include <string>
#include <map>
int main()
{
	std::map<std::string, std::string> m{ { "apple", "苹果" }, { "orange", "橙子" },
	{"pear","梨"} };
	std::map<std::string, std::string>::iterator it = m.begin();
	while (it != m.end())
	{
		//....
	}
	return 0;
}
#include <string>
#include <map>
typedef std::map<std::string, std::string> Map;
int main()
{
	Map m{ { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };
	Map::iterator it = m.begin();
	while (it != m.end())
	{
		//....
	}
	return 0;
}

4、2 auto的使用细节

4、2、1 auto与指针和引用结合起来使用

int main()
{
	int x = 10;
	auto a = &x;
	auto* b = &x;
	auto& c = x;  //引用
	cout << typeid(a).name() << endl;
	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl;
	*a = 20;
	*b = 30;
	c = 40;
	return 0;
}

4、2、2 在同一行定义多个变量

4、3 auto不能推导的场景

举报

相关推荐

0 条评论