C++引用相关知识点及实例

 变量引用

#include <iostream>
using namespace std;
int main(int argc,char* argz[])
{
	int a = 10;
	int b = 20;
	int* p = &a;	//p指向a;
	int* &pp = p;	//pp为p的引用;

	(*pp)++;		//对pp指向的值,即对p指向的a值实现++运算;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "*p = " << *p << endl;

	pp = &b;		//使pp指向b 的地址,即使p指向b;
	(*pp)++;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "*p = " << *p << endl;
	return 0;
}

指针引用 

#include <iostream>
#include <string>
using namespace std;

int main(int argc,char* argz[])
{
	int a = 10;
	int b = 20;
	int &c = a;	//声明c为a的引用;
	int q;

	c = b;		//将b的值赋给c,即将b的值赋给a;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	c = 100;	//将常量赋给c,即将100赋给a;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	q = (&a == &c) ? 1 : 0;	//比较a和c的地址,c为a的引用,两者地址相同。
	cout << q << endl;
	return 0;
}

函数及其返回值引用 

#include <iostream>

using namespace std;

const float pi = 3.14;
float f;

float f1(float r)
{
	f = r*r*pi;
	return f;
}

float &f2(float r)
{
	f = r*r*pi;
	return f;
}

int main()
{
	float  f1(float = 5);
	float& f2(float = 5);
	
	float  a = f1();
	float& b = f2();

	float  c = f1();
	float& d = f2();
	
	d += 1.0f;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << "d = " << d << endl;
	cout << "f = " << f << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/david_lzn/article/details/81197507
今日推荐