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 中不支援靜態區域性變數。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP