0

コードにはかなりの量のコードを格納する静的クラス関数があります。このコードが最初に使用され、現在も使用されている場所では、クラスのインスタンスを作成できないため、静的です。この関数の機能は、クラスのインスタンスが既に作成されているコードベースの他の場所で必要になります。

とにかく、同じ関数の非静的バージョンと静的バージョンを作成しなくても、静的関数を使用してポーリングできるすべてのコードを収容する非静的関数を、クラス インスタンスを初期化できない場所で作成できます。他の場所で実際のインスタンスを使用して呼び出されます。

例えば

#include <iostream>

class Test
{
public:
    Test(){};
    ~Test(){};
    void nonStaticFunc(bool calledFromStatic);
    static void staticFuncCallingNonStaticFunc();
};

void Test::nonStaticFunc(bool calledFromStatic)
{
    std::cout << "Im a non-static func that will house all the code" << std::endl;
    if(calledFromStatic)
    // do blah
    else
    // do blah
}

void Test::staticFuncCallingNonStaticFunc()
{
    std::cout << "Im a static func that calls the non static func that will house all `the code" << std::endl;
    nonStaticFunc(true);
}

int main(int argc, char* argv[])
{
   // In some case this could be called as this     
   Test::staticFuncCallingNonStaticFunc();

   // in others it could be called as 
   Test test;
   test.nonStaticFunc(false);
}

その呼び出しが静的であるかどうかによって、非静的関数内でコードがわずかに変更される可能性があるため、コードの他の場所で使用される非静的メンバーへのアクセスが必要になる場合があるため、静的関数を常に使用することはできません。ただし、ほとんどのコードは同じままです。乾杯

4

2 に答える 2

5

共通部分をクラス メソッドにリファクタリングし、両方のメソッドから呼び出します。もちろん、共通パーツ メソッドで非静的メンバーにアクセスすることはできません。

class Test
{
public:
    Test(){};
    ~Test(){};
    void nonStaticFunc();
    static void staticFunc();
private:
    static void commonParts();
};

void Test::commonParts()
{
    std::cout << "Im a static func that will house all common parts" << std::endl;
    // do common stuff
}

void Test::nonStaticFunc()
{
    std::cout << "Im a non-static func that will call the common parts and do other things then" << std::endl;
    commonParts();
    // do non-static stuff
}

void Test::staticFunc()
{
    std::cout << "Im a static func that will call the common parts and then do other things" << std::endl;
    commonParts();
    // do static stuff
}

int main(int argc, char* argv[])
{
   // In some case this could be called as this     
   Test::staticFunc();

   // in others it could be called as 
   Test test;
   test.nonStaticFunc();
}
于 2012-11-30T14:20:22.870 に答える
2

これは設計上の問題であり、ハッキングして機能させるのではなく、修正する必要があると考えているため、回避策を提供しない傾向があります。

いずれにせよ、共通コードを、オブジェクトへのポインターを受け取る静的関数に分解することができます。非静的メンバーからthis呼び出す場合は渡しますが、静的関数から呼び出す場合はオブジェクトを渡しません。

class test {
   void impl( test* p ) {
       // ...
       if (p) {           // we have an object: use it
          p->dosomething();
       }
   }
public:
   void nonStaticVersion() {
      impl(this);
   }
   static void staticVersion() {
      impl(0);
   }
};

しかし、本当にこれをやりたいかどうかを再考する必要があります。何をするか考えimplて、名前を付けてください。簡単な名前とその機能の簡単な説明が見つからない場合は、簡単に記述できる単純なタスクを実行する関数ができるまでリファクタリングしてください。関数の記述が条件を持ち始めた場合、それはコードの匂いであることに注意してください (つまり、Z に応じて X または Y を実行し、if...は、関数が明確な責任を持っていないというヒントです。

于 2012-11-30T15:17:55.563 に答える