C++学习(四)—函数(一)

宏函数和内联函数

#include<iostream>

using namespace std;

#define  MYADD(x,y) ((x)+(y))

// 缺陷1:为了保证运算的完整性,需要加小括号修饰

void test01()
{
	int a = 10;
	int b = 20;
	//	int c = MYADD(a, b)*20;
	//	cout << "a+b = " << c << endl;
}

// 缺陷2:即使加入括号,仍会出现与预期不符的结果

#define MYCOMPRE(x,y) (((a) < (b)) ? (a) : (b))

int  mycompre(int a, int b)
{
	return a < b ? a : b;
}

void test02()
{
	int a = 10;
	int b = 20;
	
	//	int result = MYCOMPRE(++a, b);
	int result = mycompre(++a, b);
	cout << result << endl;
}

//	3、宏函数是不重视作用域的

//	内联函数 inline
inline void f();
inline void f() { ; };
//	1、函数的声明和实现必须同时加上 inline关键字,否则不会按照内联的方式来处理
//	2、成员函数的前面隐藏加入了 inline关键字
//	3、内联函数相对于普通函数的优势是省去了函数调用时的压栈,跳转,返回的开销,可以理解为内联函数是以空间换时间



int main()
{
	//	test01();
	test02();
	system("pause");
	return 0;
}

内联函数与编译器之间的关系

内联仅仅是给编译器一个建议,编译器不一定会接受这种建议,如果没有将函数声明为内联函数,编译器也可能将此函数当作内联编译,一个好的编译器将会内联小的,简单的函数
以下情况编译器可能考虑不会将函数进行内联编译:

  • 不能存在任何形式的循环语句
  • 不能存在过多的条件判断语句
  • 函数体不能过于庞大
  • 不能对函数进行取址操作

函数参数

#include<iostream>

using namespace std;

//	1、函数的默认参数


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

void test1()
{
	cout << f() << endl;
}


//	 注意:
//	1、如果参数列表中,有一个位置有了默认参数,那么从这个位置起从左到右都必须有参数
int f2(int a = 1, int b = 1, int c = 1)
{
	return a + b + c;
}

void test2()
{
	cout << f2() << endl;
}

//	2、函数的声明与实现只能有一个有默认参数

//	int f3(int a = 100, b = 200);
int f3(int a = 10, int b = 20)
{
	return a + b;
}

void test3()
{
	cout << f3() << endl;
}

//	2、函数的占位参数
//	用途:目前没用,后面学习符号重载的时候会用到一点

int  f4(int a,int )
{
	return a;
}

void test4()
{
	cout << f4(1, 1) << endl;
}

int main()
{
	//	test1();
	//	test2();
	//	test3();
	test4();
	system("pause");
	return 0;
}
发布了31 篇原创文章 · 获赞 8 · 访问量 3673

猜你喜欢

转载自blog.csdn.net/qq_42689353/article/details/104505266
今日推荐