7.8函数 1

来源:互联网 发布:黑咔相机软件 编辑:程序博客网 时间:2024/04/29 01:37

7.8.1 C语言变参函数

int F(int num,...){
  int*p=&num+1;
  int n=0;
  for(int i=0;i!=num;i++)
      n+=*p++;
   return n;

}

利用传进来的参数本质是按顺序存在F的堆栈中,利用指针访问。但还是要知道传进来的类型,不然指针类型不对肯定运行出错。


7.8.2 函数指针和指针函数

1.指针函数说的是返回值为指针的函数。

2.函数指针是指向函数的指针。  

指向函数的指针

1. bool (*pf)(const string &, const string &);

这个语句将 pf 声明为指向函数的指针,它所指向的函数带有两个 const

string& 类型的形参和 bool 类型的返回值。

 

2. 函数指针类型相当地冗长。使用 typedef 为指针类型定义同义词,可将函

数指针的使用大大简化:(第2.6 节):

typedef bool(*cmpFcn)(const string &, const string &);

该定义表示 cmpFcn 是一种指向函数的指针类型的名字。该指针类型为“指

向返回 bool 类型并带有两个 const string 引用形参的函数的指针”。在要使

用这种函数指针类型时,只需直接使用 cmpFcn即可,不必每次都把整个类型声

明全部写出来。

 

3. 在引用函数名但又没有调用该函数时,函数名将被自动解释为指向函数的指

针。

 

4. 可使用函数名对函数指针做初始化或赋值

cmpFcn pf1 = 0; //ok: unbound pointer to function

cmpFcn pf2 =lengthCompare; // ok: pointer type matches function's type

pf1 =lengthCompare; // ok: pointer type matches function's type

pf2 = pf1; // ok:pointer types match

此时,直接引用函数名等效于在函数名上应用取地址操作符:

cmpFcn pf1 =lengthCompare;

cmpFcn pf2 =&lengthCompare;

函数指针只能通过同类型的函数或函数指针或 0 值常量表达

式进行初始化或赋值。

指向不同函数类型的指针之间不存在转换:

 

5. 指向函数的指针可用于调用它所指向的函数。可以不需要使用解引用操作

符,直接通过指针调用函数:

pf("hi","bye"); // equivalent call: pf1 implicitly dereferenced

(*pf)("hi","bye"); // equivalent call: pf1 explicitly dereferenced

 

1.      把指向函数的指针作为参数传入:

voiduseBigger(const string &, bool(const string &, const string &));

voiduseBigger(const string &, bool (*)(const string &, const string &));

两种等价。

 

2.      返回指向函数的指针:

int (*ff(int))(int*, int);

阅读函数指针声明的最佳方法是从声明的名字开始由里而

外理解。

 

7. 指向重载函数的指针

C++ 语言允许使用函数指针指向重载的函数:

extern voidff(vector<double>);

extern voidff(unsigned int);

// which functiondoes pf1 refer to?

void(*pf1)(unsigned int) = &ff; // ff(unsigned)

指针的类型必须与重载函数的一个版本精确匹配。如果没有精确匹配的函

数,则对该指针的初始化或赋值都将导致编译错误

0 0
原创粉丝点击