通常,非 static 数据成员存在于类类型的每个对象中。不像普通的数据成员,static 数据成员独立于该类的任意对象而存在;每个 static 数据成员是与类关联的对象,并不与该类的对象相关联。
正如类可以定义共享的 static 数据成员一样,类也可以定义 static 成员函数。static 成员函数没有 this 形参,它可以直接访问所属类的 static 成员,但不能直接使用非 static 成员。
使用 static 成员而不是全局对象有三个优点。
The name of a static member is in the scope of the class, thereby avoiding name collisions with members of other classes or global objects.
static 成员的名字是在类的作用域中,因此可以避免与其他类的成员或全局对象名字冲突。
Encapsulation can be enforced. A static member can be a private member; a global object cannot.
可以实施封装。static 成员可以是私有成员,而全局对象不可以。
It is easy to see by reading the program that a static member is associated with a particular class. This visibility clarifies the programmer's intentions.
通过阅读程序容易看出 static 成员是与特定类关联的。这种可见性可清晰地显示程序员的意图。
考虑一个简单的表示银行账户的类。每个账户具有余额和拥有者,并且按月获得利息,但应用于每个账户的利率总是相同的。可以按下面的这样编写这个类
class Account {
public:
// interface functions here
void applyint() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double); // sets a new rate
private:
std::string owner;
double amount;
static double interestRate;
static double initRate();
};
可以通过作用域操作符从类直接调用 static 成员,或者通过对象、引用或指向该类类型对象的指针间接调用。