C++(泛型编程)学习笔记【3】

来源:互联网 发布:公司单页网站源码 编辑:程序博客网 时间:2024/05/24 01:23

1.指针数组与数组指针:

指针数组:int *p [10] 顾名思义首先是一个10个元素的数组,然后每一个元素是一个int 型的指针;

数组指针:int (*P) [10] 首先是一个指针,是一个指向int [10] 数组的指针。

看一段代码:

#include <iostream>

 #include <typeinfo>

using namespace std;

int main()

{  int vInt=10; 

int arr[2]={10,20};    i

nt *p=&vInt; 

int **p2p=&p;   

int *parr[2]={&vInt,&vInt}; 

int (*p2arr)[2]=&arr; 

 cout<<"Declaration [int vInt=10] type=="<<typeid(vInt).name()<<endl; 

cout<<"Declaration [arr[2]={10,20}] type=="<<typeid(arr).name()<<endl; 

cout<<"Declaration [int *p=&vInt] type=="<<typeid(p).name()<<endl; 

cout<<"Declaration [int **p2p=&p] type=="<<typeid(p2p).name()<<endl; 

cout<<"Declaration [int *parr[2]={&vInt,&vInt}] type=="<<typeid(parr).name()<<endl; 

cout<<"Declaration [int (*p2arr)[2]=&arr] type=="<<typeid(p2arr).name()<<endl; 

return 0; }

 运行的结果如下:(我在前面加了行号#XX)

#01 Declaration [int vInt=10] type==int

#02 Declaration [arr[2]={10,20}] type==int *

#03 Declaration [int *p=&vInt] type==int *

#04 Declaration [int **p2p=&p] type==int * *

#05 Declaration [int *parr[2]={&vInt,&vInt}] type==int **

#06 Declaration [int (*p2arr)[2]=&arr] type==int (*)[2]

通过这个实例应该可以明白数组与指针之间的关系了。

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2.C++的函数指针:

 void test(int a, int b)     //某函数定义

{

   cout<<a+b<<endl;

}

void (*pf) (int, int)  ;          //定义指向void (int, int)类型函数的指针:pf

pf = test;

pf = &test;                          //两种赋值方式都可以

pf(3,2);

(*pf) (3,2);                         //两种调用方式都可以

 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 3.函数声明与定义:

函数声明以及类的声明时语句后一定要有分号,函数定义时不用(也可以有分号(visual studio));

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

===================================================================================================================

标注:

1.typeid【C++的typeid】

原创粉丝点击