C ++中静态成员函数的用途? [英] Purpose of a static member function in C++?
问题描述
如果每个成员函数每个类只包含一次(要由所有实例共享),那么声明成员函数static的目的究竟是什么?它是一个被声明为const的函数,因为它修改了特定类型的数据(在这种情况下是静态数据成员)?
If each member function is only contained once per class (to be shared by all instances) what exactly is the purpose of declaring a member function static? Is it like a function being declared const, in that it modifies a particular type of data (in this case, static data members)?
推荐答案
正常的成员函数需要一个类实例来运行。静态方法可以直接调用而无需先创建类的实例。
Normal member functions require a class instance to run. Static methods can be called directly without first creating an instance of the class.
正常方法:
MyClass myClass;
myClass.NormalMethod();
静态方法:
MyClass::StaticMethod();
所以正常的方法对于使用类数据的函数是完美的。如果一个方法不需要使用类数据,那么它将是一个可能被静态的候选对象。
So normal methods are perfect for functions that work with the class data. If a method doesn't need to work with the class data, then it would be a candidate for possibly being made static.
这篇关于C ++中静态成员函数的用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!