一 static变量在class中的使用
class中声明static变量,s_value的存在不依赖class的object实例,只属于class。
class Something
{
public:
static int s_value; //声明
};
int Something::s_value = 1; //定义
int main()
{
Something first;
Something second;
first.s_value = 2;
std::cout << first.s_value << '\n';
std::cout << second.s_value << '\n';
return 0;
}
输出
2
2
二 static 成员变量的定义和初始化
在上面的例子中,class中static int s_value; 只是给编译器声明有这个变量,还需要我们对变量进行定义,因为static成员不依赖于一个class object。如上面的例子,需要定义。
int Something::s_value = 1; // defines the static member variable
上面的定义实例化static变量,并初始化,如果不赋值的话,默认是0
有一点要注意,不要在头文件中对static变量进行实例化
三 内联初始化
如果一个static 成员是一个const类型或者const enum类型的话,可以在class中定义初始化。如下
class Whatever
{
public:
static const int s_value = 4; // a static const int can be declared and initialized directly
};
从c++11开始,static constexpr成员也可以在类中进行实例化,如下:
#include <array>
class Whatever
{
public:
static constexpr double s_value = 2.2; // ok
static constexpr std::array<int, 3> s_array = { 1, 2, 3 }; // this even works for classes that support constexpr initialization
};
四 static成员函数
同static成员变量一样,static成员函数属于class不属于特定object,由于不属于特定oject因此没有*this指针
class Something
{
private:
static int s_value;
public:
static int getValue() { return s_value; } // static member function
};
int Something::s_value = 1; // initializer
int main()
{
std::cout << Something::getValue() << '\n';
}
static 函数可以在class外定义,如下:
class IDGenerator
{
private:
static int s_nextID; // Here's the declaration for a static member
public:
static int getNextID(); // Here's the declaration for a static function
};
// Here's the definition of the static member outside the class. Note we don't use the static keyword here.
// We'll start generating IDs at 1
int IDGenerator::s_nextID = 1;
// Here's the definition of the static function outside of the class. Note we don't use the static keyword here.
int IDGenerator::getNextID() { return s_nextID++; }
int main()
{
for (int count=0; count < 5; ++count)
std::cout << "The next ID is: " << IDGenerator::getNextID() << '\n';
return 0;
}
五 c++不支持satic构造函数
C++不支持static构造函数,如果变量可以直接初始化如第一个例子,不需要在构造函数。下面的例子通过定义一个static class成员的方式对static变量进行初始化。
class MyClass
{
private:
static std::vector<char> s_mychars;
public:
class _init // we're defining a nested class named _init
{
public:
_init() // the _init constructor will initialize our static variable
{
s_mychars.push_back('a');
s_mychars.push_back('e');
s_mychars.push_back('i');
s_mychars.push_back('o');
s_mychars.push_back('u');
}
} ;
private:
static _init s_initializer; // we'll use this static object to ensure the _init constructor is called
};
std::vector<char> MyClass::s_mychars; // define our static member variable
MyClass::_init MyClass::s_initializer; // define our static initializer, which will call the _init constructor, which will initialize s_mychars
网友评论