C++ 中的 static 关键字与 Java 中的 static 关键字


在 C++ 或 Java 中,我们可以使用 static 关键字。它们在大多数情况下是相同的,但在这两门语言之间也存在一些基本差异。让我们看看 C++ 中的 static 和 Java 中的 static 之间的区别。

静态数据成员在 Java 和 C++ 中基本上是相同的。静态数据成员是类的属性,并且它被所有对象共享。

示例

public class Test {
   static int ob_count = 0;
   Test() {
      ob_count++;
   }
   public static void main(String[] args) {
      Test object1 = new Test();
      Test object2 = new Test();
      System.out.println("The number of created objects: " + ob_count);
   }
}

输出

The number of created objects: 2

示例

#include<iostream>
using namespace std;
class Test {
   public:
      static int ob_count;
      Test() {
         ob_count++;
      }
};
int Test::ob_count = 0;
int main() {
   Test object1, object2;
   cout << "The number of created objects: " << Test::ob_count;
}

输出

The number of created objects: 2

静态成员函数 - 在 C++ 和 Java 中,我们可以创建静态成员函数。它们也是该类的成员。但也有一些限制。

  • 静态方法只能调用其他静态方法。
  • 它们只能访问静态成员变量。
  • 它们不能访问 'this' 或 'super'(仅限 Java)。

在 C++ 和 Java 中,静态成员可以在不创建对象的情况下访问。

示例

//This is present in the different file named MyClass.java
public class MyClass {
   static int x = 10;
   public static void myFunction() {
      System.out.println("The static data from static member: " + x);
   }
}
//This is present the different file named Test.Java
public class Test {
   public static void main(String[] args) {
      MyClass.myFunction();
   }
}

输出

The static data from static member: 10

示例

#include<iostream>
using namespace std;
class MyClass {
   public:
      static int x;
      static void myFunction(){
         cout << "The static data from static member: " << x;
      }
};
int MyClass::x = 10;
int main() {
   MyClass::myFunction();
}

输出

The static data from static member: 10

静态块:在 Java 中,我们可以找到静态块。这也称为静态子句。它们用于类的静态初始化。静态块中编写的代码将只执行一次。这在 C++ 中不存在。

在 C++ 中,我们可以声明静态局部变量,但在 Java 中不支持静态局部变量。

更新于: 2019年7月30日

535 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.