gpt4 book ai didi

c++ - C++中函数指针的地址

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:23 26 4
gpt4 key购买 nike

<分区>

我不清楚调用返回的值是什么:

&next, fp, *fp, &return_func_ptr, fp_ptr, &fp_ptr, *fp_ptr

它们似乎都给我值 1。什么意思?

还有,我要怎么申报

int (*return_f())(char)

不使用 typedef 接收参数?

#include <iostream>

int next(int n){
return n+99;
}

// returns pointer to a function
typedef int (*fptr)(int); // using typdef
fptr return_func_ptr(){
return next;
}

int f(char){
return 0;
}
int (*return_f())(char){ // how do you pass a parameter here?

// std::cout << "do something with " << param << std::endl;
return f;
}



int main()
{

int x = 5;

// p points to x
int *p = &x;
std::cout << "x=" << x << std::endl; // 5, value of x
std::cout << "&x=" << &x << std::endl; // 0x7fff6447a82c, address of x
std::cout << "p=" << p << std::endl; // 0x7fff6447a82c, value of p is address of x
std::cout << "*p=" << *p << std::endl; // 5, value of x (p dereferenced)
std::cout << "&p=" << &p << std::endl; // 0x7fff6447a820, address of p pointer

// change value of x thru p
// p = 6; // error, can't set int* to int
*p = 6;
std::cout << "x=" << x << std::endl; // 6


int y = 2;
// int *q = y; // error can't initiate with type int, needs int*


// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp

fp = &next; // fp points to function next(int)
fp = next;
std::cout << "&next=" << &next << std::endl; // 1, address of function?
std::cout << "fp=" << fp << std::endl; // 1, value is address of function?
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp?
std::cout << "*fp=" << *fp << std::endl; // 1, address of function?

// calling function thru pointer
int i = 0;
i = (*fp)(i);
std::cout << "i=" << i << std::endl; // 99
i = fp(i);
std::cout << "i=" << i << std::endl; // 198



// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1

int j = fp_ptr(1);
std::cout << "j=" << j << std::endl; // 100

}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com