简体   繁体   English

声明没有定义的 static 成员

[英]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:结果:

  1. The code can run successfully.代码可以成功运行。
  2. There is no output.没有 output。 So the code do not call the constructor and destructor of b .所以代码不会调用b的构造函数和析构函数。

My question:我的问题:

  1. when class A declares b , how to find b's definition?当 class A声明b时,如何找到b's定义?
  2. why the code can run successfully?为什么代码可以成功运行?
#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

Live居住

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM