1.上
//非引用形参
#include<iostream>
#include<string>
using namespace std;
int AddOne(int x)//非引用,普通形参,就是把实参copy进去
{
x = x + 1;
return x;
}
void AddTwo(int *px)//指针形参-非引用形参-copy
{
*px = *px + 2;
}
void AddThree(int& x)//引用形参,传入的是真正的实参。不是copy
//非const形参不能传const实参
{
x = x + 3;
}
//指针复习:可以将初始化为const类型的对象初始化为非const对象
//但不可以将非const指向非const对象
int add_2(const int x, const int y)//const形参既可以穿非const实参,也可以传非const实参
//非const实参可以传给const形参
{
return x + y;
}
//void AddFour(const int *ip)
//{
// *ip = *ip + 2;//出错,指针指向的一个常量,不能修改
//}
//const形参有什么用,希望传进去的参数copy的副本不可以修改,只能读
//void addone(const int x)
//{
// x = x + 1;//出错,x是const形参,传进去就不可以修改
//
//}
int main()
{
int a=1, b=2, c=3;
AddTwo(&b);//把b的地址copy一个传进去,对地址解引用+2,还是加到了原来的值上
//改变的还是原来的对象
AddThree(c);
cout << b << endl;
cout <<AddOne(a) << endl;
cout << c << endl;
// const形参
const int m = 8;
const int n = 9;//可以用const对象初始化非const对象
system("pause");
return 0;
}
2.下-习题
#include<iostream>
#include<string>
using namespace std;
int getBiggetr(int x, const int *p)//比较
{
return x > *p ? x : *p;
}
void swap(int *x, int *y)//交换
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 9,b=2;
cout << getBiggetr(2,&a) << endl;
swap(&a, &b);
cout << a << b << endl;
system("pause");
return 0;
}