[英]declare static member without definition
class A
declares static variable b
, but there is NO definition of b
in the code. class A
声明了 static 变量b
,但代码中没有定义b
。
Result:结果:
b
.所以代码不会调用b
的构造函数和析构函数。My question:我的问题:
A
declares b
, how to find b's
definition?当 class A
声明b
时,如何找到b's
定义?#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>
class B
{
public:
B()
{
std::cout << "go into B constructor" << std::endl;
};
B::~B()
{
std::cout << "go into B destructor" << std::endl;
};
void output()
{
std::cout << "B output" << std::endl;
}
};
class A
{
public:
static B b;
int i;
};
//B A::b;
int main()
{
A a;
// A::b.output();
return 0;
}
In this code A::b
is not used at all, so no definition needed :在这段代码A::b
根本没有使用,所以不需要定义:
int main()
{
A a;
return 0;
}
In this code A::b
is used, so definition of A::b is needed :在此代码中使用了A::b
,因此需要定义 A::b:
int main()
{
A::b.output();
return 0;
}
Fot non-const static data member to be initialized, this has to be done explicitly, for example add BA::b
after class A {... }: Fot非常量 static 数据成员被初始化,这必须明确地完成,例如在 class A {... } 之后添加BA::b
:
class A
{
public:
static B b; // declaration of A::b
int i;
};
B A::b; // definition of A::b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.