C++: Static Class Definition

In C++, the static specifier is only meaningful when applied on functions and variables. But surprisingly, C++ allows static to be used on a class definition:

static class Car
{
    int _speed;
};

This specifier is useless on the class definition since it does not mean anything! This compiles successfully with with Visual C++, only generating a C4091 warning:

warning C4091: 'static ' : ignored on left of 'Car' when no variable is declared

This hints at the reason why C++ allows static on a class definition. It is to support the definition of a class and the creation of a static object of that class in a single statement:

static class Car { int _speed } fooCar;

The above is equivalent to:

class Car
{
    int _speed;
};

static Car fooCar;

 

  

  

posted on 2013-02-02 22:09  androidme  阅读(402)  评论(0编辑  收藏  举报

导航