静态成员函数在c++中的实现
Implementation of static member function in C++
我想知道静态成员函数是否本质上意味着它在编译时在内存中获得一个地址,并且在整个程序中从不更改它。
因此,它使我们有机会在指针中传递它而不必担心,因为我们总是确定我们将永远在同一个地方找到它
所有函数在编译时都有静态地址分配给它们(对于动态加载的库来说有点不同)。成员函数(静态或非静态)是一个标准函数,它的地址在编译时已知。否则链接器是如何工作的?
- 使用静态函数可以调用构造函数,该构造函数被声明为私有。
下面是代码,
#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;
}
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的