在c++中,static
是属于类而不是实例的关键字或修饰符。 因此,不需要实例来访问静态成员。 在c++中,static
可以是字段,方法,构造函数,类,属性,操作符和事件。
c++ static关键字的优点
内存效率: 现在我们不需要创建实例来访问静态成员,因此它节省了内存。 此外,它属于一种类型,所以每次创建实例时不会再去获取内存。
使用static
关键字声明字段称为静态字段。它不像每次创建对象时都要获取内存的实例字段,在内存中只创建一个静态字段的副本。它被共享给所有的对象。
它用于引用所有对象的公共属性,如:account
类中的利率(rateofinterest
),employee
类中的公司名称(companyname
)等。
下面来看看看c++中静态(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;
}
上面代码执行结果如下-
201 sanjay 6.5
202 calf 6.5
下面来看看看c++中static
关键字的另一个例子,统计创建对象的数量。
#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;
}
上面代码执行结果如下-
201 sanjay
202 calf
203 ranjana
total objects are: 3