Mad*_*dal 5 c++ pointers function-pointers function
我有两个问题:
Q1)函数名称本身是指针吗?
如果它们是指针,那么它们中存储了什么值?
否则,如果它们不是指针,那么它们是什么以及它们中存储了什么值?
如果我们认为函数名是指针.然后 :
void display(){...}
int main ()
{
void (*p)();
**p=display; //Works (justified**, because we are assigning one pointer into another)
**p=&display; //Works (Not justified** If function name is a pointer (let say type*) , then &display is of datatype : type**. Then how can we assign type** (i.e. &display) into type * (i.e. p)??)
**p=*display; //Works (Not justified** If function name is a pointer ( type *) ,then, how can we assign type (i.e. *display) into type * (i.e. p) ?? )
}
Run Code Online (Sandbox Code Playgroud)
再次,
cout<<display<<";"<<&display<<";"<<*display;
打印类似于:
为0x1234;为0x1234; 0x1234的
[1234只是例如]
[我的天啊!这怎么可能 ??如何指向指针的地址,指向的地址和指向地址的值都相同?]
Q2)用户定义的函数指针中存储了什么值?
考虑这个例子:
void display(){...}
int main()
{
void (*f)();
f=display;
f=*f; // Why does it work?? How can we assign type (i.e. *f ) into type * (i.e. f).
cout<<f<<";"<<&f<<";"<<*f;
//Prints something like :
0x1234;0x6789;0x1234
}
Run Code Online (Sandbox Code Playgroud)
[前两个输出是合理的... 但是指针(它指向的地址)中的值如何等于存储在指向地址中的值?]
再次:
f=*********f; // How can this work?
Run Code Online (Sandbox Code Playgroud)
我在网上搜索了它,但所有可用的信息都是关于用法和示例代码来创建函数指针.他们都没有说出他们是什么或者他们与普通指针的区别.
所以我必须遗漏一些非常基本的东西.请指出我缺少的东西.(抱歉我的初学者是无知的.)
n. *_* m. 10
函数名称本身是指针吗?
不可以.但是,在某些情况下,函数可以自动转换为指向函数的指针.该标准在第4.3段中说明:
函数类型T的左值可以转换为"指向T的指针"的prvalue.结果是指向函数的指针.
(函数名称指定左值,但可以有其他函数类型的左值).
在你的例子中
p = display;
p = *p;
Run Code Online (Sandbox Code Playgroud)
正是这种自动转换.display并且*p是函数类型的左值,并且在需要时,它们以静默方式自动转换为指向函数的类型.
p = *display;
Run Code Online (Sandbox Code Playgroud)
这里转换发生两次:首先display转换为*操作符的指针,然后取消引用,然后再次转换为=操作符的指针.
cout << display << ";" << &display << ";" << *display;
Run Code Online (Sandbox Code Playgroud)
这里,display被转换为指针operator <<; &display已经是一个指针,因为它&是一个普通的地址获取运算符; 并*display转换为指针,operator <<在其内部display转换为指针operator *.
f = *********f;
Run Code Online (Sandbox Code Playgroud)
在这个表达式中有很多这种转换.自己算吧!
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |