/*ca55a_c++_函数参数传递_非引用形参
txwtech
非引用形参,传参数,就是copy
1.普通形参
* 非const形参
* const形参,不能修改
2.指针形参
* 非const指针形参
* const指针形参
//AddOne2(a2);//error C2664: “void AddOne2(int *)”: 无法将参数 1 从“const int”转换为“int *”
不能把const传给非const
非const实参可以传给const形参
const可以传给const
3.复制实参的局限性
非引用形参,传参数,就是copy,如果一个数组比较大,比如int a[1000000];
有些情况下,类里面不能复制实参
class Dog
{
int a[100000];
}
void doA(Dog dog)
{
//传递数组a时,执行拷贝,就会开销很大,花费时间长。
}
引用形参。。。
*/
/*ca55a_c++_函数参数传递_非引用形参
txwtech
非引用形参,传参数,就是copy
1.普通形参
* 非const形参
* const形参,不能修改
2.指针形参
* 非const指针形参
* const指针形参
//AddOne2(a2);//error C2664: “void AddOne2(int *)”: 无法将参数 1 从“const int”转换为“int *”
不能把const传给非const
非const实参可以传给const形参
const可以传给const
3.复制实参的局限性
非引用形参,传参数,就是copy,如果一个数组比较大,比如int a[1000000];
有些情况下,类里面不能复制实参
class Dog
{
int a[100000];
}
void doA(Dog dog)
{
//传递数组a时,执行拷贝,就会开销很大,花费时间长。
}
引用形参。。。
*/
#include <iostream>
using namespace std;
void AddOne(int x)//非引用形参,传参数,就是copy
{
x = x + 1;
}
//传指针的copy,地址的拷贝
void AddTwo(int *px)//指针形参,(指针是非引用)
{
*px = *px + 2;
}
//引用形参,传递c本身,
void AddThree(int& x)//引用形参,传递c本身,
{
x = x + 3;
}
int add(int x, int y)
{
return x + y;
}
int add2(const int x, const int y)//const形参
{
return x + y;
}
//非引用const 形参,传参数,就是copy
void AddOne1(const int x)//非引用const 形参,传参数,就是copy
{
//x = x + 1; //const值不能修改
}
//demo3
void AddOne2( int *ip)//
{
*ip = *ip + 1;
}
//const指针,值不能修改
void AddTwo2(const int *px)//const指针,值不能修改
{
//*px = *px + 2;//const指针,值不能修改
}
int add3(const int *px, const int *py)
{
return *px + *py;
}
//函数重载,函数名一样,参数不一样
void fcn(int i)//函数重载,函数名一样,参数不一样
{
cout << i << endl;
}
void fcn(double i)//函数重载
{
cout << i << endl;
}
int getBigger(int x, const int *y)
{
return x > *y ? x : *y;
}
//void swap(int x, int y)//在main函数里面,两个值实际没有交换
//{
// int temp;
// temp = x;
// x = y;
// y = temp;
//}
void swap(int *x, int *y)//在main函数里面,两个值实现了交换
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a, b, c;
a = 1;
b = 2;
c = 3;
cout << "a加之前: " << a << endl;
AddOne(a);
cout << "a加之后: " << a << endl;
cout << "c加之前: " << c << endl;
AddThree(c);//引用形参,传递对象c本身,
cout << "c加之后: " << c << endl;
cout << "b加之前: " << b << endl;
AddTwo(&b);
cout << "b加之后: " << b << endl;
//demo2
int kk,kk2;
const int m = 8, n = 9;
kk=add(m, n);
cout <<"m+n= "<< kk << endl;
kk2 = add2(m, n);
cout << "add2: const m+n= " << kk2 << endl;
//demo3
int a1, b1, c1;
const int a2=10;
const int b2=20;
const int c2=30;
a1 = 1, b1 = 2, c1 = 3;
AddOne2(&a1);
//AddOne2(a2);//error C2664: “void AddOne2(int *)”: 无法将参数 1 从“const int”转换为“int *”
//不能把const传给非const
int kk3;
kk3=add3(&a1, &a2);//非const实参可以传给const形参
//
cout << "习题1" << endl;
int aa = 2, bb=9;
cout << "the bigger is: "<<getBigger(2,&bb) << endl;
cout << "交换前:" << aa << "," << bb<< endl;
swap(&aa, &bb);
cout << "交换后" <<aa<<","<<bb<< endl;
return 0;
}