第一周 从 C 到C++ - PKU[课程作业]程序设计与算法(三)C++面向对象程序设计_C++ Object Oriented Programming week01

 

1:简单的swap

#include 
using namespace std;
class A
{
	public:
	int x;
	int getX() { return x; }	
};
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;
}

 

2:难一点的swap

#include 
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;
	return 0;
}

 

3:好怪异的返回值

#include 
using namespace std;
int & getElement(int * a, int i)
{
	return a[i];
}
int main()
{
	int a[] = {1,2,3};
	getElement(a,1) = 10;
	cout << a[1] ;
	return 0;
}

 

4:神秘的数组初始化

#include 
using namespace std;

int main()
{
	int * a[] = {NULL,NULL,new int, new int[6]};
	
	*a[2] = 123;
	a[3][5] = 456;
	if(! a[0] ) {
		cout << * a[2] << "," << a[3][5];
	}
	return 0;
}
/*
	指针数组
	a[0]->NULL
	a[1]->
	a[2]->123
	a[3]->x,x,x,x,x,456
*/

 

你可能感兴趣的:(course,assignment,Cpp)