【问题标题】:What are static methods? How and when are they used?什么是静态方法?它们如何以及何时使用?
【发布时间】:2013-09-29 12:49:48
【问题描述】:

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

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

【问题讨论】:

  • 你的 C++ 教科书是怎么说的?
  • 静态函数和静态方法是不同的东西,但都是以static开头的。
  • 一个函数“不包含”任何“成员”。
  • 没有课本,自己上网自学
  • @Arihant 如果可以的话,买一本教科书,再糟糕的教科书也比互联网更可靠。

标签: c++ static-methods static-members


【解决方案1】:

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

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

【讨论】:

  • 我真的不喜欢你的解释。这更多的是关于静态方法的规范,而不是“什么是静态方法”,尽管可能很清楚那些理解其规范的人是什么。我认为,this 是更好的解释
【解决方案2】:

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

当然,由于 struct 与 class 相似,只是 struct 成员默认为 public,因此这也适用于 struct。

使用静态函数和变量的一个原因是使用factory pattern 为类创建对象工厂。另一个用途是Singleton Pattern

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-23
    • 2011-07-04
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多