你如何在c ++中创建一个静态函数/方法?

时间:2014-04-26 04:33:36

标签: c++ static

我只是在学习C ++。我已经了解C和Java。有人可以告诉我如何在C ++中创建静态方法/函数,就像我在Java中一样。例如,仅仅为了练习,我正在编写一个包含标准信息(姓名,学号,gpa等)的学生课程。我想创建一个静态方法/函数,它将返回创建的学生对象的总数。我在Java中知道它会是:

public static int getNumStudents () {
    return totalStudentsCreated; // global variable
}

谢谢。 :)

2 个答案:

答案 0 :(得分:2)

以下是C ++中的内容

class Student {
   private:
      static int totalStudentsCreated;
   public:
      static int getNumStudents();
};

int Student::totalStudentsCreated = 0;

int Student::getNumStudents() { return totalStudentsCreated; }

应该包含在C ++教科书中

答案 1 :(得分:0)

静态方法

您需要将方法放在Student类中并将其标记为静态。你需要记住,不幸的是,C ++在这个时间点不允许使用const静态方法。您还将只能操作“全局”,“文件范围静态”或“静态成员数据”变量。

这一切都很小。你可以这样写:

class MyClass {
   public:
      static int getNumStudents() { return totalStudentsCreated; }
};

然后你会这样调用这个方法:

int numStudents = MyClass::getNumStudents();

int numStudents = myClass.getNumStudents();

虽然后者可能无法与所有编译器一起使用,但请尽量坚持使用前一种变体。

静态函数(没有类)

如果您只需要一个没有外部类的静态函数,那么您可以编写以下内容:

static int getNumStudents() { return totalStudentsCreated; }

然后按如下方式使用它:

int numStudents = getNumStudents();
相关问题