简体   繁体   English

使用静态函数将非静态对象存储在类中

[英]Store Non-Static Object in Class with Static Functions

i have two classes (non-static) A & (static) B. I am trying to store Object A into B so that i can use its functions in funcB(). 我有两个类(非静态)A和(静态)B。我试图将对象A存储到B中,以便可以在funcB()中使用其功能。 However i do know that static classes cannot store non-static variables & functions. 但是我确实知道静态类不能存储非静态变量和函数。 is there anyway to get pass this rather than converting Class A into a static class? 无论如何要通过传递而不是将A类转换为静态类?

class A
{
   public:
          A();
          void funcA();
   private:
          int A;
};

class B
{
   public:
         B(A *objA);
         static void funcB();
   private:
         A *objA;
};

edit: I stated static class to make it easier to explain. 编辑:我说静态类,以使其更容易解释。 i did not know the correct term. 我不知道正确的用语。 So the question is actually: How do i use a non-static member from a static function? 所以问题实际上是:如何使用静态函数中的非静态成员?

You can not access anything that is specific to an instance of a class from a static function by itself. 您不能通过静态函数本身访问特定于类实例的任何内容。 A static function has no "this" pointer (the compiler passes a pointer to the instance of the object calling the function for non-static functions). 静态函数没有“ this”指针(编译器将指针传递给调用该函数的对象实例用于非静态函数)。 You can get around this by passing a pointer to the object you want to modify, but then why are you using a static function? 您可以通过将指针传递到要修改的对象来解决此问题,但是为什么要使用静态函数呢? My advice would be to avoid what it seems like you are trying to do, but I provided 2 ways to do it below (as a good learning example). 我的建议是避免您尝试做的事情,但是我在下面提供了2种方法(作为一个很好的学习示例)。

See below for an example of using 请参阅下面的使用示例

    #include <iostream>

using namespace std;

class A
{
   public:
    A(int value) : a(value){}
          void funcA();
   public:
          int a;
};

class B
{
   public:
         B()
         {
             objA = new A(12);
         }

         void funcB2()
         {
             B::funcB(*objA);
         }

         static void funcB(A const & value)
         {
            cout << "Hello World! " << value.a << endl;
         }

   private:
         A *objA;
};

int main()
{
    A a(10);
    B::funcB(a);

    B b;
    b.funcB2();
    return 0;
}

I think you just should not make design like this. 我认为您不应该这样设计。 A static function is initialized when the non-static members are not ready. 当非静态成员尚未准备就绪时,将初始化静态函数。 You said "the class A, links to many other classes and has stored many other information. Class B on the other hand, has to be static due to some windows API threading condition." 您说:“类A链接到许多其他类,并存储了许多其他信息。另一方面,由于某些Windows API线程条件,类B必须是静态的。” . In this case, can you change your design and turn A into static class? 在这种情况下,您可以更改设计并将A转换为静态类吗?

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

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