初始化静态成员类(用于信号处理程序)

时间:2016-12-30 02:54:07

标签: c++ multithreading event-handling static-members

在使用静态成员之前,我已按照此Example初始化它们。

我想在我的代码中做同样的事情。但它不起作用。 海湾合作委员会告诉我:  undefined reference to MainClass::TheStatic1

代码:

#include <iostream>
using namespace std;    

基类构造函数inits&#39; a&#39;给定参数

class MyStaticBase {

public:
  MyStaticBase(int iSetA):a(iSetA){};
  ~MyStaticBase(){}
  int a;

  void SayHello(){
    std::cout << "Say Hello from Static Instance: " << a <<  std::endl;
  }    
};

派生类使用特定值初始化Base类。

//  First derived Class
class MyStaticDerived1:public MyStaticBase{
public:
  MyStaticDerived1():MyStaticBase(1){  }    
};

// Second derived Class
class MyStaticDerived2:public MyStaticBase{
public:
  MyStaticDerived2():MyStaticBase(2){}    
};

包含两个类似的成员,只有构造函数调用才有区别,当它们是从它们的基类派生时。

class MainClass {    
public:
 MainClass(){};
 ~MainClass(){};

 static MyStaticDerived1 TheStatic1;
 static MyStaticDerived2 TheStatic2;    
};      

主要

 int main() {

  MainClass TheMainClass;

  // [PROBLEM]: gcc:undefined reference to `MainClass::TheStatic1'
  TheMainClass.TheStatic1.SayHello();
  TheMainClass.TheStatic2.SayHello();
}

尝试在main()中解决(jap,其中一些只是猜测)

  // Attempts:
  // MyStaticDerived1::MyStaticDerived1(); // error: cannot call constructor ‘MyStaticDerived1::MyStaticDerived1’ directly [-fpermissive]
  // MainClass::TheStatic1 TheStatic1;   //error: expected ‘;’ before ‘TheStatic1’
  // MainClass::TheStatic2 TheStatic2 = 0;
  // MainClass::TheStatic1();
  // MyStaticDerived1 MainClass::TheStatic1; //qualified-id in declaration before ‘;’ token
  // MyStaticDerived1 MainClass::TheStatic1{}; //qualified-id in declaration before ‘{’ token

为什么我要这样做?

MyStaticDerived是线程处理类,由信号处理程序(SIGCHILD)调用。此处理程序只能访问静态成员。管理两组进程,因此我需要两个类似的线程处理类。

1 个答案:

答案 0 :(得分:0)

复制粘贴代码以获取工作示例。感谢@ThomasMatthews和@ user4581301使这个答案成为可能。请参阅主函数上方的解决方案。 Futur信息请在@ThomasMatthews提供的链接中找到。

#include <iostream>
using namespace std;

class MyStaticBase {
public:
  MyStaticBase(int iSetA):a(iSetA){};
  ~MyStaticBase(){}
  int a;

  void SayHello(){
    std::cout << "Keep a signalhandler SHORT\n"
        << "Just set a flag =)\n"
        << "thx to all!\n"
        << " Instance: " << a <<  std::endl;
  }
};

//  Derived Classes
class MyStaticDerived1:public MyStaticBase{
public:
  MyStaticDerived1():MyStaticBase(1){  }

};
class MyStaticDerived2:public MyStaticBase{
public:
  MyStaticDerived2():MyStaticBase(2){}

};

class MainClass {

public:
 MainClass(){};
 ~MainClass(){};

 static MyStaticDerived1 TheStatic1;
 static MyStaticDerived2 TheStatic2;
};

// [ Solution ]
MyStaticDerived1 MainClass::TheStatic1;
MyStaticDerived2 MainClass::TheStatic2;

int main() {
  MainClass TheMainClass;
  TheMainClass.TheStatic1.SayHello();
  TheMainClass.TheStatic2.SayHello();
}