c++ - Namespace::* 和传统的 * 有什么区别吗?

标签 c++ pointers namespaces function-pointers member-function-pointers

class C {
    public:
    int a;
    int f();
};

int C::f() { return 0; }




int main() {


    C c {1};

    int(C::*pmf)() = &C::f;
    // int(*pmf)() = &C::f; -> error can not convert int(*C::f)() to int(*f)().


}
ram 中的 Namespace::* 和 * 之间有什么区别还是只是由编译器检查?是语法糖吗?

最佳答案

当然:https://isocpp.org/wiki/faq/pointers-to-members

Non-static member functions have a hidden parameter that corresponds to the this pointer. The this pointer points to the instance data for the object.


这些函数在物理上是不可互换的,因为成员有一个额外的参数 - 您从中调用它的对象。你看不到它,但编译器把它放在那里。当该对象丢失时,编译器显然会提示。这不像 C#,其中每个函数都是一个成员函数,有些只是碰巧是静态的(有趣的事实:当将 C# 函数传递给第三方时,它所附加的对象会随之传递以允许稍后有效调用。您可能会也可能无法在此处模拟类似的东西)。

关于c++ - Namespace::* 和传统的 * 有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66150715/

相关文章:

抽象类的 C++ 继承

c# - 在 C# 中使用 native C++ 代码 - std::vector 的问题

c++ - emacs - 如果函数包含在命名空间中 (C++),则 "go to beginning of the function"不起作用

C strcpy 函数和 char*

c - 为什么此 C 结构初始化代码会产生总线错误?

java - 在java中创建xml时仅在根节点添加命名空间

c++ - & 在构造函数中使用 const

c - 指针未给出正确的值

Python 生成器让我困惑

Javascript:在同一命名空间内的数组中引用变量