0

私は2つのクラス(非静的)Aと(静的)Bを持っています.funcB()でその関数を使用できるように、オブジェクトAをBに格納しようとしています。ただし、静的クラスは非静的変数と関数を格納できないことは知っています。クラスAを静的クラスに変換するのではなく、これを渡す方法はありますか?

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

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

編集:説明を簡単にするために静的クラスを述べました。正しい用語を知りませんでした。質問は実際には次のとおりです。静的関数から非静的メンバーを使用するにはどうすればよいですか?

4

2 に答える 2

1

静的関数自体から、クラスのインスタンスに固有のものにアクセスすることはできません。静的関数には「this」ポインターがありません(コンパイラーは、非静的関数の関数を呼び出すオブジェクトのインスタンスへのポインターを渡します)。これを回避するには、変更するオブジェクトへのポインターを渡しますが、なぜ静的関数を使用しているのでしょうか。私のアドバイスは、あなたがやろうとしているように見えることを避けることですが、私はそれを行うための2つの方法を以下に提供しました(良い学習例として)。

使用例については、以下を参照してください

    #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;
}
于 2013-01-29T04:25:36.013 に答える
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." . In this case, can you change your design and turn A into static class?

于 2013-01-29T04:14:16.803 に答える