1 函数操作
int fact(int val);
int main() {
int j = fact(5);
cout << "5! is " << j << endl;
return 0;
}
int fact(int val) {
int ret = 1;
while (val > 1) {
ret *= val--;
}
return ret;
}
2 实参和形参区别
形参是函数定义时出现,实参是调用时出现的。
3 void fcn(const int i){ fcn能够读取I,但是不能向写值}
4 数组引用形参
int k[10]={0,1,2,3,4,5,6,7,8,9};
print(k);
void print(int (&arr)[10]) {
for (auto elem:arr) {
cout << elem << endl;
}
}
5 传递多维数组
Int *matrix[10]; //10个指针构成的数组
Int (*matrix)[10]; //指向含有10个整数的数组的指针
6 initializer_list是一种模板类型,对象的元素值永远是常量。
void error_msg(initializer_list<string> li) {
for (auto beg = li.begin(); beg != li.end(); ++beg) {
cout << *beg << " ";
}
cout << endl;
}
7 引用返回左值
char &get_val(string &str, string::size_type ix) {
return str[ix];
}
string s("a value");
get_val(s, 0) = 'A';
cout << s << endl;
输出:
A value
char &get_val(string str, string::size_type ix) {
return str[ix];
}
string s("a value");
get_val(s, 0) = 'A';
cout << s << endl;
输出:
a value
8 下面的函数效果一样
int &get(int *arry, int index) {
return arry[index];
}
int &get2(int (&arry)[10], int index) {
return arry[index];
}
9 重载和const形参
一个拥有顶层const的形参无法和另一个没有顶层const的形参区分开
Record lookup(Account&);
Record lookup(const Account&); //对于前者来说是新函数
10 函数指针
bool (*pf)(const string &,const string &);
bool b1=pf("hello","goodbye");
bool b2=(*pf)("hello","goodbye”);//两者等价