数据结构期末复习(C++部分)

数据结构期末复习(C++部分)

1.参数传递

1)值传递

形参是实参的拷贝,改变形参的值不会影响实参的值

传递是单向的 从实参到形参

参数的值只能传入,不能传出

pass in the copy

2)引用传递

pass in the variable itself doesn't have to make copy save space

引用即为实参的别名,对引用的操作相当于对实参直接操作

语法:类型名&引用名=目标变量int&a=b

对数组的引用 int(&a)[4]=b 类型 (&引用名)[数组中元素数量]=数组名

对指针的引用 int(*&)a=b 类型(*&)应用名=指针

引用被创建是必须初始化,引用类型必须与目标类型相同

int main(){

int a=6;

int b=8;

void passByValue(int x)

{x=9;}

void passByReference(int &x)

{x=10;}

int a; &a; // address of a

int& a = b; // the "&" now means you're declaring a reference to "b".

Of course, when declaring a refence, you must immidiately assign it to something. References must always refer to something, they can't refer to nothing. So...

int& a; // not valid.

int& a = b; // valid.

To use it with function, you need to declare the function this way, to accept referneces: void function(int& a); // takes a reference to an int.

3)指针传递

形参指向实参地址的指针,当对形参的指向操作时,就相当于对实参本身进行的操作

总结一下指针和引用的相同点和不同点:

★相同点:

●都是地址的概念;

指针指向一块内存,它的内容是所指内存的地址;而引用则是某块内存的别名。

★不同点:

●指针是一个实体,而引用仅是个别名;

 basic difference

pointer have the freedom to move around and point to different value 

 the reference is assigned one time and it just become the reference to that location in the memory.

https://www.youtube.com/watch?v=sxHng1iufQE

●引用只能在定义时被初始化一次,之后不可变;指针可变;引用“从一而终”,指针可以“见异思迁”;

●引用没有const,指针有const,const的指针不可变;(具体指没有int& const a这种形式,而const int& a是有     的,  前者指引用本身即别名不可以改变,这是当然的,所以不需要这种形式,后者指引用所指的值不可以改变)

●引用不能为空,指针可以为空;

●“sizeof 引用”得到的是所指向的变量(对象)的大小,而“sizeof 指针”得到的是指针本身的大小;

void swapint(int *a,int *b)
{
int temp;
temp=*a;
a=*b;
*b=temp;
}
void swapint(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

若定义:char s[20]="programming",*ps=s ;

则不能表示字符‘o’的是() 。

  • ps+2
  • s[2]
  • ps[2]
  • *(ps+2)
ps+2指向o字符的地址 而不是'o'

2.函数指针

void traverse(void (*visit)(List_Entry&))

https://zhuanlan.zhihu.com/p/37306637

函数返回类型(*指针变量)(形参列表)

int (*fp)(int a)

函数指针的应用

void List::traverse(void(*visit)(int &))

{for(int i=0;i<count;i++)

(*visit)(entry[i]);}

void print(int &x)

{cout<<x<<endl;}

mylist.traverse(print);

3.内存分配

猜你喜欢

转载自www.cnblogs.com/wwqdata/p/12092962.html