为什么成员函数指针需要 & 而不是普通函数指针?
Why is & needed for member function pointers, not for normal function pointers?
我理解我的第二个陈述"why &一般的函数指针不需要",因为函数名本身就是函数的地址。
我不明白的是为什么成员函数指针严格需要'&' ?
例子:普通函数指针:
int add(int a, int b) {
return (a + b);
}
int (*fp)(int, int);
fp = add;
(*fp)(2, 3) // This would give me addition of a and b, i.e. 5
成员函数指针
class ABC {
public:
int i;
ABC() { i = 0; }
int addOne(int j) {
return j + 1;
}
};
// Member function pointer
int (ABC::*mfp)(int);
// This is what I am talking about. '&' in below line.
mfp = &ABC::addOne;
ABC abc;
std::cout << (abc.*mfp)(2) << std::endl;
在我看来,成员函数指针的寻址操作符是必要的,因为声明的右侧(rhs)是常量而不是变量。
我们不会说
int (ABC::*mfp)(int);
mfp = ABC::addOne();
因为这将调用一个函数
而且,作用域解析符operator::在c++操作符优先级表
中具有最高的优先级。https://github.com/MicrosoftDocs/cpp-docs/blob/master/docs/cpp/cpp-built-in-operators-precedence-and-associativity.md::操作符在rhs上的任何其他操作符之前求值。我猜编者会想:"嗯……那是什么?这应该是一个函数,但是…",然后看到地址操作符,并知道开发人员需要什么。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针