资讯详情

04c++

一、引用:本质是指针常量

引用的基本语法

#include<iostream> using namespace std;  int main() {  int a = 10;  //引用语法:数据类型 &别名 = 原名;  int& b = a; ///引用必须初始化     初始化后引用//不可以改变  cout << "a = " << a << endl;  cout << "b = " << a << endl;  b = 100;  cout << "a = " << a << endl;  cout << "b = " << a << endl;      return 0; }

引用作函数参数

功能:函数传参时,可以用引用的技术修饰实参

优点:无需指针即可使用

void swap02(int* a, int* b) {  int tmp = *a;  *a = *b;  *b = tmp; } //引用函数传参 void swap03(int& a, int& b) {  int tmp = a;  a = b;  b = tmp; }   int main() {  int a = 10;  int b = 20;   //swap02(&a, &b);  swap03(a, b);//可以改变实参   cout << a << endl;  cout << b << endl;   return 0; }

3.引用作为函数的返回值

#include<iostream> using namespace std;  ///引用作函数返回值 //1,不要返回引用局部变量 int& test04() {  int a = 10;  return a; }  函数调用可作为左值 int& test05() {  static int a = 10.//静态变量,存储在整个区域,系统在程序结束后释放整个区域的数据  return a; } int main() {  //int& ret = test04();   //cout << ret << endl;//第一次正确,因为保留了编译器  //cout << ret << endl;///   int& ret2 = test05();   cout << ret2 << endl;  cout << ret2 << endl;   test05() = 1000;//如果引用函数的返回值,该函数可作为左值调用  //test05返回的是a,即ret二是a的别名,test05 == a,则ret也为1000  cout << ret2 << endl;  cout << ret2 << endl;  system("pause");  return 0; }

4、常量引用

#include<iostream> using namespace std;  void show(const int& a) {  //a = 1000;//常量引用函数,防止误操作改变实参  cout << a << endl;  }  int main() {  int a = 10;  //int& ret = 10.//引用本身需要一个合法的内存空间,err  //const int& ret = 100;//bigo这里相当于  int tmp = 100; const int& ret = 100;   show(a);  cout << a << endl;  return 0; }

二、高级函数

1.函数的默认参数

注意事项:

1)如果某个位置有默认参数,则从左到右必须有默认值 假如函数 声明 有默认参数, 函数 实现 没有默认参数!!!也就是说,声明和实现只能有一个默认参数

#include<iostream> using namespace std;  int func1(int a, int b = 20, int c = 30) {  return a   b   c; } //注:1.如果某个位置已经有默认参数,则从这个位置向后,从左到右必须有默认值 假如函数 声明 有默认参数, 函数 实现 没有默认参数!!!!声明和实现只能有默认参数  int main() {  int ret = func1(10);  cout << ret << endl;   int ret1 = func1(10, 30);//如果我们输入数据,使用输入数据,不使用默认数据  cout << ret1 << endl;    return 0;  }

2、占位参数

#include<iostream> using namespace std;  void func2(int a, int = 10) ///占位参数也可以有默认值 {   cout << "liu yi hong" << endl;  }  int main() {  func2(10, 10);  func2(10);    return 0; }

3、函数重载

1)语法,函数重载

  • 在同一功能域下
  • 函数名称相同
  • 函数参数或者或者

函数的返回值不能作为函数重载的条件

2)函数重载注意事项

#include<iostream> using namespace std;  //1.引用作为重载的条件  void func(int& a)//int& a = 十、违法 {  cout << "func int& a  " << endl; }  void func(const int& a) {  cout << "func const int& a  " << endl; }  //2.函数重载遇到默认参数会导致二义性,尽量不要使用默认参数  int main() {  int a = 10;   func(a);   func(10);    return 0; }

标签: 04c热过载继电器lrd

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台