c++ code:(7)basics2

 

//输出5,3,完成swap
//*************solution1*************
#include<iostream>

using namespace std;

class  A
{
public:
	int x;
	int getX() { return x; }

private:

};

void swap(A &a,A &b)
{
	int tmp = a.x;
	a.x = b.x;
	b.x = tmp;
}

int main()
{
	A a, b;
	a.x = 3;
	b.x = 5;
	swap(a,b);
	cout << a.getX() << " "<<b.getX();
	return 0;
}

//*************solution2*************
#include<iostream>
using namespace std;

void swap(int * &a,int * &b)
{
	int *tmp = a;
	a=b;
	b = tmp;
}

int main()
{
	int a=3, b=5;
	int * pa = &a;
	int * pb = &b;
	swap(pa,pb);
	cout << *pa << " " << *pb << endl;
	cout << a << " "<<b;
	return 0;
}

 

//reference as return value of fun
//引用函数的返回值
#include<iostream>
using namespace std;

int & getelement(int *arr, int i)
{
	return arr[i];
}

int main()
{
	int a[] = { 1,2,3 };
	getelement(a, 1)=10;
	cout << a[1];
	return 0;
}
//array intilization using dynamic memory
#include<iostream>
using namespace std;

int main()
{
	int * a[] = { 0,0,new int[6],new int[6] };
	* a[2] = 123;
	a[3][5] = 456;
	if (!a[0])
	{
		cout << *a[2] <<" "<< a[3][5] << endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值