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



在使用静态成员之前,我像在此示例中一样初始化它们。

我想在我的代码中执行同样的操作。但是它行不通。GCC告诉我: undefined reference to MainClass::TheStatic1

代码:

#include <iostream>
using namespace std;    

基类构造函数'

class MyStaticBase {
public:
  MyStaticBase(int iSetA):a(iSetA){};
  ~MyStaticBase(){}
  int a;
  void SayHello(){
    std::cout << "Say Hello from Static Instance: " << a <<  std::endl;
  }    
};

衍生的类启动具有其特定值的基类。

//  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

为什么我要这样做?

神秘派生是线程处理类,由信号处理程序(Sigchild)调用。该处理程序只能访问静态成员。管理两组流程,因此我需要两个类似的线程处理类。

复制工作示例的粘贴代码。THX到@thomasmatthews和 @user4581301使此答案成为可能。请参阅主要函数上方的解决方案。未来信息请在@thomasmatthews提供的链接中查找。

#include <iostream>
using namespace std;
class MyStaticBase {
public:
  MyStaticBase(int iSetA):a(iSetA){};
  ~MyStaticBase(){}
  int a;
  void SayHello(){
    std::cout << "Keep a signalhandler SHORTn"
        << "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();
}

相关内容

  • 没有找到相关文章

最新更新