一、引用型函数参数
1、可以将引用用于函数的参数,这时形参就是实参的别名,通过形参可以直接修改实参变量的值,同时还可以避免传参的过程,减小函数调用开销,提高代码执行效率。
#include <iostream> using namespace std; void swap1(int* x,int* y){ *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y; } void swap2(int& x,int& y){ x = x ^ y; y = x ^ y; x = x ^ y; } int main(void) { int a = 3,b = 5; //swap1(&a,&b); swap2(a,b); cout << "a=" << a << ",b=" << b << endl; return 0; }
2、引用型函数参数有可能意外的修改实参值,如果不希望修改实参本身,可以将形参声明为常引用,提高传参效率的同时还可以接收常量型的实参
#include <iostream> using namespace std; struct Teacher{ char name[100]; int age; double salary; }; void print(const Teacher& t){ cout << "我叫" << t.name << ",今年" << t.age/*++*/ << "岁,工资是" << t.salary << endl; } int main(void) { const Teacher wangjl={"王建立",45,8000.5}; print(wangjl); print(wangjl); return 0; }
#include <iostream> using namespace std; struct A{ int data; int& func(void){ return data; } }; int& foo(void){ int num = 100; return num;//返回局部变量引用,危险! } int main(void) { A a = {100}; int& ra = a.func(); cout << "&a.data=" << &a.data << endl; cout << "&ra=" << &ra << endl; //ra = 200; //a.data = 200; a.func() = 200; cout << a.data << endl;//200 //int& rf = foo(); //cout << rf << endl;//100 return 0; }
二、指针
#include <iostream> using namespace std; void func(void){ cout << "func" << endl; } int main(void) { int a = 10; int* p = &a; int** pp = &p;//二级指针,ok int& r = a; //int&* pr = &r;//引用的指针,error int* pr = &r;//ok,但仅是普通指针 int*& rp = p;//ok,指针的引用 //int&& rr = r;//error,引用的引用 int& rr = r;//ok,但仅是普通引用 int i=10,j=20,k=30; int* parr[3] = {&i,&j,&k};//ok,指针数组 //int& rarr[3] = {i,j,k};//error,引用数组 //但是定义数组引用(数组的别名) int arr[3] = {i,j,k}; int (&rarr)[3] = arr;//ok,数组引用 void (*pfunc)(void) = func;//函数指针 void (&rfunc)(void) = func;//函数引用 pfunc(); rfunc(); return 0; }
三、类型转化
#include <iostream> using namespace std; int main(void) { int* pi = NULL; //char c = (int)pi;//C风格强制转换 char c = int(pi);//C++风格强制转换 void* pv = pi; pi = static_cast<int*>(pv);//合理 //c = static_cast<int>(pi);//不合理 return 0; }
#include <iostream> using namespace std; int main(void) { /*volatile修饰的变量表示易变的,告诉编译器 * 每次在使用该变量时都要从内存中重写读取 * 不要直接使用之前保存在寄存器中的副本, * 防止编译器优化而引发的错误结果*/ const volatile int ci = 100; int* pci = const_cast<int*>(&ci); *pci = 200; cout << "ci=" << ci << endl;//?200 cout << "*pci=" << *pci << endl;//200 cout << "&ci=" << (void*)&ci << endl; cout << "pci=" << pci << endl; return 0; }
#include <iostream> using namespace std; int main(void) { //"\000"-->'\0'-->0 char buf[] = "0001\00012345678\000123456"; struct Http{ char type[5]; char id[9]; char passwd[7]; }; Http* ph = reinterpret_cast<Http*>(buf); cout << ph->type << endl;//0001 cout << ph->id << endl;//12345678 cout << ph->passwd << endl;//123456 return 0; }