gpt4 book ai didi

c++ - 为什么获取成员函数指针值需要在类内部进行类名限定?

转载 作者:可可西里 更新时间:2023-11-01 15:22:24 24 4
gpt4 key购买 nike

当在该类的一个成员函数中返回一个指向该类的成员函数指针时,我仍然必须指定该类。我不能简单地接受地址。例如,this code works fine :

class Foo {
public:
void func(int param) { cout << param << endl; }
void (Foo::*getPointer())(int) { return &Foo::func; }
};

但是如果在 getPointer 中我尝试简单地做:return &func 我得到这个错误:

prog.cpp: In member function 'void (Foo::* Foo::getPointer())(int)':
prog.cpp:8:43: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&Foo::func' [-fpermissive]
void (Foo::*getPointer())(int) { return &func; }

为什么我必须在我所在的上下文中指定类?

最佳答案

指针和指向成员的指针是不同的类型,我们可以从草案 C++ 标准部分 3.9.2 [basic.compound] 部分看到,其中包括指针的复合类型以及 指向非静态类成员的指针和注释:

Static class members are objects or functions, and pointers to them are ordinary pointers to objects or functions

这个问题我认为在 this quote in an answer from Johannes 中有很好的描述来自 Annotated C++ Reference Manual(ARM) :

Note that the address-of operator must be explicitly used to get a pointer to member; there is no implicit conversion ... Had there been, we would have an ambiguity in the context of a member function ... For example,

void B::f() {
int B::* p = &B::i; // ok
p = B::i; // error: B::i is an int
p = &i; // error: '&i'means '&this->i'
// which is an 'int*'

int *q = &i; // ok
q = B::i; // error: 'B::i is an int
q = &B::i; // error: '&B::i' is an 'int B::*'
}

特别是这些行:

int B::* p = &B::i; // OK

和:

p = &i; // error: '&i'means '&this->i' which is an 'int*'

展示合格名称和非合格名称之间的区别。

关于c++ - 为什么获取成员函数指针值需要在类内部进行类名限定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842429/

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