在C++中,static
是屬于類而不是實例的關(guān)鍵字或修飾符。 因此,不需要實例來訪問靜態(tài)成員。 在C++中,static
可以是字段,方法,構(gòu)造函數(shù),類,屬性,操作符和事件。
C++ static關(guān)鍵字的優(yōu)點
內(nèi)存效率: 現(xiàn)在我們不需要創(chuàng)建實例來訪問靜態(tài)成員,因此它節(jié)省了內(nèi)存。 此外,它屬于一種類型,所以每次創(chuàng)建實例時不會再去獲取內(nèi)存。
使用static
關(guān)鍵字聲明字段稱為靜態(tài)字段。它不像每次創(chuàng)建對象時都要獲取內(nèi)存的實例字段,在內(nèi)存中只創(chuàng)建一個靜態(tài)字段的副本。它被共享給所有的對象。
它用于引用所有對象的公共屬性,如:Account
類中的利率(rateOfInterest
),Employee
類中的公司名稱(companyName
)等。
下面來看看看C++中靜態(tài)(static
)字段的簡單示例。
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
}
};
float Account::rateOfInterest=6.5;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Employee
Account a2=Account(202, "Calf"); //creating an object of Employee
a1.display();
a2.display();
return 0;
}
上面代碼執(zhí)行結(jié)果如下-
201 Sanjay 6.5
202 Calf 6.5
下面來看看看C++中static
關(guān)鍵字的另一個例子,統(tǒng)計創(chuàng)建對象的數(shù)量。
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Account
Account a2=Account(202, "Calf");
Account a3=Account(203, "Ranjana");
a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
上面代碼執(zhí)行結(jié)果如下-
201 Sanjay
202 Calf
203 Ranjana
Total Objects are: 3