您的位置:首页 > 其它

函数

2016-03-18 19:38 155 查看
[b]一.Main[/b]

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
for (int i = 0; i < argc; i++)
{
cout << argv[i] << endl;
}

return 0;
}




[b]二.内联函数[/b]

为了解决调用小函数大量消耗栈空间的问题

#include <iostream>
using namespace std;

inline char* dbtest(int a)
{
return (a % 2 == 0) ? "偶":"奇";
}

int main(int argc, char *argv[])
{
cout << dbtest(2) << endl;

return 0;
}


等价于

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
cout << ((2 % 2 == 0) ? "偶":"奇") << endl;

return 0;
}


inline函数体不能过大,不能包含复杂结构(while,switch),不能直接递归调用。inline要在函数声明的时候表示,声明的时候不写,定义的时候写是错误的

内联与宏:

宏是由预处理器替代,而内联函数是通过编译实现。inline能让编译器检查出更多的错。inline是真正的函数。

[b]三.重载[/b]

函数名相同,函数的参数列表不同

避免二义性:

void x(){}
void x(int i = 0){}


[b]四.缺省默认值[/b]

某个写好的函数要添加新的参数,而原来该函数的语句未必需要新增的参数,那么为了避免对原来那些函数调用语句的修改可以使用缺省参数

#include <iostream>
#include <string>
using namespace std;

void f(int x, float s = 12.6, char t = '\n', string msg = "error"){}

int main(int argc, char *argv[])
{
f(14, 48.3, '\t', "ok");//ok
f(14, 48.3, '\t');//ok
f(14, 48.3);//ok
f(14);//ok
f();//error
//缺省默认值的参数要在参数列表最左边
// int d(int x, int y = 10), OK
// int d(int y = 10, int x), error
//默认参数在声明中给出而非定义中
return 0;
}


[b]五.static[/b]

#include<iostream>
using namespace std;

void f()
{
int a = 0;
static int b = 0;

a++;
b++;

cout << a << " " << b << endl;
}

int main()
{
for (int i = 0; i < 3; i++)
{
f();
}
/*
1 1
1 2
1 3
*/
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: