C++快速入门(命名空间/引用/函数重载/内联函数)

#include<bits/stdc++.h>

using namespace std;

namespace mynum//命名空间
{
	int x = 105;
}
using namespace mynum;//可以使用两个namespace,前提是两个命名空间没有相同变量

void Swap(int &x, int &y)//函数的引用,传递过来的是实参本身,修改x,y原来函数中的参数也会修改,类似指针
{
	int c = x;
	x = y;
	y = c;
}

struct node
{
	int x, y;
};

void fun(int i, int j = 10, int k = 100)//函数实参可以初始
{
	cout << i << j << k << endl;
}

int getMax(int x, int y)//函数重载,(参数个数或参数类型上要不同,编译时编译成getMax_int_int来进行区分)
{
	return max(x, y);
}

int getMax(int x, int y, int z)//函数重载(getMax_int_int_int)
{
	return max(x, max(y, z));
}

int getMax(int *arr, int cout)
{
	int temp = arr[0];
	for (int i = 1; i < cout; i++)
		if (temp < arr[i]) temp = arr[i];
	return temp;
}

//inline内联函数使得运行效率更高,但必须逻辑简单,只是给编译器的意见,并不一定会内联
inline double getMax(double x, double y)//函数重载,内联函数(getMax_double_double)
{
	return max(x, y);
}

int main()
{

	//引用,相当于起别名,修改任意一个,另一个都会改变
	/*
	int a = 10;
	int &b = a;//引用定义时必须初始化
	b = 100;
	cout << b << endl;
	a = 999;
	cout << a << endl;

	int x = 10, y = 20;
	cout << x << ' ' << y << endl;
	Swap(x, y);//函数的引用,类似指针
	cout << x << ' ' << y << endl;

	int*q = &a;
	cout << q << endl;
	int*& p = q;//指针的引用
	p = NULL;
	cout << q << endl;

	struct node nd1;
	nd1.x = 99;
	nd1.y = 100;
	struct node & nd = nd1;//结构体的引用
	cout << nd.x << ' ' << nd.y << endl;
	nd1.x = 66;
	nd1.y = 77;
	cout << nd.x << ' ' << nd.y << endl;

	*/



	//命名空间的使用
	//cout << mynum::x << endl;




	//函数重载
	/*
	cout << getMax(1.5, 1.6) << endl;
	cout << getMax(5, 9) << endl;
	cout << getMax(1, 2, 3) << endl;
	int arr[5] = { 1, 3, 4, 5, 2 };
	cout << getMax(arr, 5) << endl;
	*/




	//申请释放内存new,delete
	/*
	c语言中用int *malloc(sizeof(int) 和 free(int)
	int *p = new int;
	delete p;p = NULL;//防止重复回收
	int *arr = new int[10];//申请块内存
	delete[]arr;//释放块内存
	delete arr//释放的是数组的第一个内存
	*/
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值