静态变量重新初始化
有人可以帮助我理解,如果创建了具有非默认构造函数的新实例,为什么下面的类中定义为静态的变量 masterID 会重新初始化?
static unsigned int masterID=0;
class game{
public:
unsigned int m_id;
unsigned int m_players;
// default constructor
game():m_id(masterID++){
}
// another constructor using a game instance
game(game g): m_id(masterID++){
...
}
// copy constructor
// copy constructor
game(const game &o)
: m_id(o.m_id), m_players(o.m_players)
{ }
// assignment operator
game& operator =(const game o){
m_id = o.m_id;
m_players = o.m_players;
return *this;
};
使用此代码,只要我使用默认构造函数创建实例,例如
game g1, g2;
m_id 的值为 0, 1, 2,... 等。
但是,如果现在我创建第三个实例,因为
game g3(g2);
g3 的 m_id 又是0.
我不明白这里发生了什么。
Could someone help me understand, why the variable masterID, defined static, in the following class re-initializes, if a new instance with a non-default constructor is created?
static unsigned int masterID=0;
class game{
public:
unsigned int m_id;
unsigned int m_players;
// default constructor
game():m_id(masterID++){
}
// another constructor using a game instance
game(game g): m_id(masterID++){
...
}
// copy constructor
// copy constructor
game(const game &o)
: m_id(o.m_id), m_players(o.m_players)
{ }
// assignment operator
game& operator =(const game o){
m_id = o.m_id;
m_players = o.m_players;
return *this;
};
with this code, as long as I create instances using the default constructor, such as
game g1, g2;
the m_id takes on values as 0, 1, 2,... etc.
But, if now I create a third instance as
game g3(g2);
the m_id for g3 is again 0.
I don't understand what is happening here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
static unsigned int masterID=0;
位于您的.h
文件中。它不应该在那里:按照您现在的方式,您会在每个编译单元中获得一个单独的静态变量,其中包含您的.h
文件。正确的方法是在类中声明
masterID
static ,并在单个.cpp
文件中对其进行初始化。在您的 .h 文件中:
在您的 cpp 文件中:
This is because
static unsigned int masterID=0;
is in your.h
file. It should not be there: the way you have it now, you get a separate static variable in each compilation unit that includes your.h
file.The right way of doing it is to declare
masterID
static in your class, and initialize it in a single.cpp
file.In your .h file:
In your cpp file: