学习要点:
1 如果传入的参数非指针,非数组,就用引用吧。这样可以节约空间。
2 如果传入的参数不需要改变,加上const吧。表明参数是只读的。
3 函数指针和重载的结合使用。
4 如果传入的引用参数可能会被输入常数,加上const
#include <iostream>
#include <string>
using namespace std;
void Swap(int *a,int *b)
{
int n = *a;
*a = *b;
*b = n;
}
void Swap(int &a,int &b) //参数是引用
{
int n = a;
a = b;
b = n;
}
//形参尽量使用引用,因为值传递意味着要复制一遍变量。
//形参尽量使用const,如果不使用const就意味你想要改变引用变量的值。
//数组不必写引用 需要修改不加const
void Print( const int& n) //const
{
cout << &n << '\t' << hex << n << endl;
cout << dec;
}
struct Window
{
string text;
int x,y;
int width,height;
};//GUI
void input(Window& r)
{
cout << "请输入窗口标题 xy坐标 宽度高度" <<endl;
cin >> r.text >> r.x >> r.y >> r.width >> r.height ;
}
void print(const Window& r) //const表示是只读访问 并不代表是常量
{
cout << "窗口标题" << r.text;
cout << " 从" << r.x << "," << r.y;
cout << "到" << r.x+r.width << "," << r.y+r.height <<endl;
}
int main()
{
int m = 10, n = 20;
Swap(&m,&n);//传递地址
cout << "m = " << m << ",n = " << n << endl;
Swap(m,n); //使用引用参数
cout << "m = " << m << ",n = " << n << endl;
//函数指针与重载到结合使用。
void (*f)(int *,int *) = &Swap;
f(&m,&n);
cout << "m = " << m << ",n = " << n << endl;
void (*g)(int &,int &) = &Swap;
g(m,n);
cout << "m = " << m << ",n = " << n << endl;
//正常到引用接受到是变量。
Print(m);
Print(n);
//接收常量 临时空间 或者保护参数不被修改,则加上const
Print(123);
//接收常量必须有const 否则报错
// error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
Print(m+n);
Window w;
input(w);
print(w);
}