java基础改学C++(六)指针(2)函数的指针、指针的指针
//函数的指针、指针的指针
一、函数的指针和指向函数的指针变量
函数在编译时被分配给一个入口地址。这个入口地址就称为函数的地址,也是函数的指针。像数组一样,C++语言规定,函数名就代表函数的入口地址
#include <iostream>
#include <cmath>
using namespacestd;
//上节的函数
void copy(char*p1,char *p2,int start){
p1+=start;
while((*p2++ = *p1++));
}
//先不用理这个
double f1(double x){
return x*x-3;
}
//不用理这个,先看main !!!
double binarySeperate(double (*func) (double)){//形参用指向函数的指针变量func接受函数名
//其实就是把参数加一下,再改改下面的f1成形参名
double x0,x1,x2,precision =1e-6;
do {
cout<<"input the bound of the answer(two numbers)\n";
cin>>x1>>x2;
// 用func调用函数,实际调用的是实参函数
} while ((func(x1)*func(x2))>=0);
do {
if (func(x1)<func(x2)) {
int t = x1;
x1 = x2;
x2 = t;
}
x0 = x1/2+x2/2;
if (func(x0)>0)
x1 = x0;
else
x2 = x0;
} while (abs(func(x0))>precision);
return x0;
}
int main(){
// 函数的指针 定义形式:
void (*p) (char*,char*,int) = copy; //按照这个样式写,和数组名差不多
p = copy; //相当于声明变量,再赋值
// 同数组名一样,函数名copy代表函数在内存中的入口地址,是一个常量,不可被赋值。
// 指向函数的指针变量 p可以先后指向不同的同种类型的函数,但不可作加减运算。
// Demo 这个函数不重要,关键是对比不同点!!!!!!!!!看指针写的不同点
// 二分法解方程(只能解出一个根)第一版,正常写法,第二版,指针写法
一、普通做法
double x0,x1,x2,precision = 1e-6;
do {
cout<<"input the bound of the answer(two numbers)\n";
cin>>x1>>x2;
} while ((f(x1)*f(x2))>=0);
do {
if (f(x1)<f(x2)) {
int t = x1;
x1 = x2;
x2 = t;
}
x0 = x1/2+x2/2;
if (f(x0)>0)
x1 = x0;
else
x2 = x0;
} while (abs(f(x0))>precision);
cout<<x0;
}
// 二、指针。重在对比!!!
double (*func) (double) =f1;
double result1 =binarySeperate(f1);
cout<<result1<<endl;
double result2 =binarySeperate(func);//这俩都一样,调用函数,实参为函数名(地址)或存好的地址
cout<<result2<<endl;
double r = (*func)(6);
cout<<r<<endl<<result1<<endl<<result2<<endl;
//指针做返回值不是很难,直接看看图算了:
// 二、 指针的数组以及指针的指针:
// 指针数组是一个数组,其元素均为指针类型的数据。也就是说,指针数组中的每一个元素可以放地址:
//
int *arr[5];//每个元素都是指针
//加括号更易理解:
(int*) arr2[5];//int类型的指针,有5个,首地址就是 arr2
不好理解 看demo吧==
再看一个 :
int a[13] = {1,22,3,4,5,6,7,4,34,4,4,3,34};
int *b[2];
b[1] = &a[9];
int c = b[1][2];
// c 是 3。自己理解
// 关于字符指针数组:
更难的东西考试不考。
}