[英]Why can't print member function's address by it's name?
I have learned that function name equals function address like this: 我已经知道函数名称等于函数地址,如下所示:
void func(){}
void main() { cout << func; }
But when I used the same code to print memeber function, it went wrong. 但是,当我使用相同的代码打印memeber函数时,它出错了。
class Test{
public:
void func() {}
void printFunc1() {
cout << func << endl;
}
void printFunc2() {
void (Test::*ptrtofn)() = &Test::func;
cout << (void*&)ptrtofn << endl;
}
};
printFunction2()
work but printFunction1()
doesnt printFunction2()
工作但printFunction1()
What makes the difference? 有什么区别?
Member function's name is not member function's address? 成员函数的名称不是成员函数的地址? Is there any reason?
有什么缘故吗?
member function != standalone function 成员函数!=独立函数
Only standalone functions can be converted to pointer implicitely. 只有独立函数才能隐含地转换为指针。
4.3 Function-to-pointer conversion [conv.func]
4.3函数到指针的转换[conv.func]
1 An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.1函数类型T的左值可以转换为“指向T的指针”的prvalue。结果是指向函数的指针。 58
58
58) This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained.
58) 此转换从不适用于非静态成员函数,因为无法获取引用非静态成员函数的左值。
Please understand "func" is the member function of the class . 请理解“func”是该类的成员函数。 accessing it directly is itself a compilation error .Rather you should try to use pointer to member function as you have done in printFunction2: Else if func is function outside the class scope .Then it can be done as below :
直接访问它本身就是一个编译错误。你应该尝试使用指向成员函数的指针,就像你在printFunction2中所做的那样:如果func是类范围之外的函数,那么它就可以了。那么它可以按如下方式完成:
#include <iostream>
using namespace std;
void func() {cout<<"\n calling func\n";}
void printFunc1() {
cout << endl<<hex<<(void*)func << endl;
}
int main() {
printFunc1();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.