c++ - 为什么不能通过名称打印成员函数的地址?

标签 c++ class

我了解到函数名等于函数地址 像这样:

void func(){}
void main() { cout << func; }

但是当我用同样的代码打印memeber函数时,就出错了。

class Test{
public:
    void func() {}
    void printFunc1() {
    cout << func << endl;
   }
    void printFunc2() {
    void (Test::*ptrtofn)() = &Test::func;
    cout << (void*&)ptrtofn << endl;
  }
};

printFunction2() 有效,但 printFunction1() 无效

有什么区别?

成员函数名不是成员函数地址? 有什么理由吗?

最佳答案

成员函数 != 独立函数

只有独立函数可以隐式转换为指针。

4.3 Function-to-pointer conversion [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. 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.

关于c++ - 为什么不能通过名称打印成员函数的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34433172/

相关文章:

php - 我可以使用字符串连接在 PHP 中定义类 CONST 吗?

javascript - 声明 JavaScript 成员函数的最佳实践

c++ - istringstream 无效错误初学者

C++ 函数接收枚举作为其参数之一

c++ - 传递对象和面向对象的设计最佳实践

c++ - 具有多种类型的类数组?如何访问数组中的一种类型?

python使用内部类动态创建类

c++ - 使用 init-methods 来避免使用 new 分配对象——这是糟糕的设计吗?

C++ 清理成功,构建失败,目录丢失?

c++ - CRTP编译错误