什么是静态方法?如何以及何时使用它们

What are static methods? How and when are they used?

本文关键字:何时使 静态方法 什么      更新时间:2023-10-16

我正在寻找有关C++静态方法的信息。我搜索了一下,但老实说,我无法清楚地理解一件事。

静态函数

是那些只包含静态数据成员的函数吗?

C++类中的静态方法(如 Java 类的方法(是无需实际实例化对象或类实例即可使用的方法。

使用类的标准非静态方法的唯一方法是创建对象或实例化类的实例。 然后,当您使用这些方法时,您正在对类的特定对象或实例进行操作。

静态方法有一些限制。 例如,不能在静态方法中使用 this 指针。 这是因为类的静态方法不与特定的特定对象相关联。 相反,它是一种不绑定到任何特定对象的通用方法。

我对类中静态方法的看法是,当我这样做时,我正在创建一个特定的命名空间,类名,然后添加一个只能使用该特定命名空间访问的函数。

中的静态变量在应用程序启动时创建,无需创建类的特定实例即可访问该变量。 静态变量也由类的所有实例共享。

因此,

对于差异的示例(即兴发挥,因此可能存在编译错误(:

class myAclass {
public:
  myAclass();     // constructor
  void function1 (int iValueSet);   // a standard method
  static void functionStatic (int iValueSet);  // a static method
private:
  int iValue;                // an object specific variable
  static int iValueStatic;   // a class general variable shared by all instances of this class
};
int myAclass::iValueStatic = 0;  // init the class static variable
    myAclass::myAclass () : iValue (0)
{
}
void myAclass::function1 (int iValueSet)
{
   iValue = iValueSet;    // set the iValue for this particular object
   iValueStatic = iValueSet;  // set the shared iValueStatic for all instances
}
void myAclass::functionStatic (int iValueSet)
{
//    iValue = iValueSet;   // ERROR this is not allowed as iValue is not static
    iValueStatic = iValueSet;   // works since iValueStatic is static
}

然后如何使用这个类:

myAclass jj;    // create an object instance
jj.function1(5);   // access the non-static method to change the object data
myAclass::functionStatic(8);  // set the static iValueStatic
当然,由于结构类似于

类,只是结构成员默认是公共的,这也适用于结构。

使用

静态函数和变量的一个原因是使用工厂模式为类创建对象工厂。 另一个用途是单例模式。

类的静态方法没有this指针。 这意味着它们无法访问实例成员数据。 方法(静态或其他(不包含数据成员。 (但是,它们可以在堆栈或堆上声明变量。

静态方法通常用类名(myClass::foo()(调用,因为你不必声明类的实例来使用它们,但也可以用实例(myInstance.foo()(调用。