静态成员函数在c++中的实现

Implementation of static member function in C++

本文关键字:实现 c++ 函数 静态成员      更新时间:2023-10-16

我想知道静态成员函数是否本质上意味着它在编译时在内存中获得一个地址,并且在整个程序中从不更改它。

因此,它使我们有机会在指针中传递它而不必担心,因为我们总是确定我们将永远在同一个地方找到它

所有函数在编译时都有静态地址分配给它们(对于动态加载的库来说有点不同)。成员函数(静态或非静态)是一个标准函数,它的地址在编译时已知。否则链接器是如何工作的?

    使用静态函数可以调用构造函数,该构造函数被声明为私有
  • 下面是代码,

    #include <iostream>
    using namespace std;
    class STATIC
    {
    private:
           STATIC()
           {
               cout<<"In Constructor..."<<endl;
           }
    public:
           static void fun()
           {
           STATIC a1;
           }
    };
    int main()
    {
        STATIC::fun();
    }
    
  • 这是Static成员函数的使用之一。

静态成员函数只是一个普通的自由函数,有一个有趣的名字。指向函数的指针与指向静态成员函数的指针兼容。

非静态成员函数是接收额外的隐式隐藏this参数作为第一个参数的函数。然而,指向非静态成员函数的指针与指向函数的指针不兼容。

要使用指向成员函数的指针调用非静态成员函数,需要提供一个实例…而且语法也很奇怪:如果x是对象引用,则(x.*member_ptr)(...),如果x是指针,则(x->*member_ptr)(...)

指向非静态成员函数的指针和指向函数的指针是不兼容的类型,并且没有可移植的方法来转换它们。如果你知道这个实例,并且你想有一个可调用对象来调用它的一个非成员函数,你可以使用(在c++ 11中)std::function包装一个lambda。

#include <functional>
#include <string.h>
#include <iostream>
struct Foo {
    int x;
    Foo(int x) : x(x) {}
    void bar() { std::cout << x << std::endl; }
    static void baz() { std::cout << "Heren"; }
};
int main(int argc, const char *argv[]) {
    void (Foo::*f)() = &Foo::bar; // Non-static function member pointer
    void (*g)() = &Foo::baz;      // Static member function = function
    Foo x(42);
    (x.*f)(); // Prints 42
    g();      // Prints "Here"
    // Portable way to call a non-static member function just using ff()
    std::function<void()> ff = [&x](){ x.bar(); };
    ff(); // Prints 42 too
    // Hack zone... just to show that on many compilers
    // even a pointer to non-static member function is just
    // a pointer to a function that accepts however `this`
    // as an extra first parameter.
    void (*hack)(void *);
    memcpy(&hack, &f, sizeof(hack));
    hack(&x); // Prints 42 too on g++/clang++ (NOT PORTABLE!!)
    return 0;
}