什么是C ++中的静态函数 [英] what are static functions in C++

查看:144
本文介绍了什么是C ++中的静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1.我在理解为什么我们需要静态成员函数时感到困惑. 2.声明静态成员函数会怎样? 3.当静态成员函数具有类范围或属于类而不是类的对象时,这意味着什么?

解决方案

静态函数是仅在静态函数上运行的那些函数数据-它们与该类的任何实例都不相关,并且无法访问或调用任何非静态变量或函数.它们没有this指针.

您也可以通过类名而不是通过实例变量来访问不同的变量.


在回答问题1:为什么需要静态成员函数?"

我过去曾想将成员函数用作WNDPROC时使用过它们.
由于您不能使用非静态方法作为WndProc的回调,因此您需要创建一个静态方法.然后,必须从该静态方法中确定与特定窗口相关的c ++对象实例.

这种做法使人感到有些不舒服,被称为"Thunking".


我首先在 Win32 ++ [ ^ ]
我假设如果您需要添加一些会影响该类的每个实例的行为,则可以在MFC中找到类似的代码


. >

1.I have confusion in understanding why do we need static member functions? 2.What happens when we declare static member functions? 3.What does it means when static member functions have class scope or belong to class rather than objects of the class?

解决方案

Static functions are those that operate only on static data - they are not related to any instance of the class, and cannot access or call any non-static variables or functions. They do not have a this pointer.

You access trhen differently too - via the class name, rather than via an instance variable.


In answer to question 1, "Why do we need static member functions?"

I''ve used them in the past when I wanted to use a member function as a WNDPROC.
Since you can''t use a non-static method as the callback that WndProc is, you need to create a static method. Then from within that static method you must determine which c++ object instance is pertinant to the particular window.

The practise leaves one feeling a little unlean, and is known as Thunking.


I first came across this use in the source-code for Win32++[^]
I''d assume that similar code was found within MFC


if you need to add some behavior which affect every instance of that class, static method and properties do it for you.


这篇关于什么是C ++中的静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆