C++学习笔记(七)-- 引用作为形参 引用与函数指针

学习要点:

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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值