5

定数静的変数aを持つ基本クラスAがあります。クラスBのインスタンスが静的変数aに対して異なる値を持つ必要があります。できれば静的初期化を使用して、これをどのように達成できますか?

class A {
public:
    static const int a;
};
const int A::a = 1;

class B : public A {
    // ???
    // How to set *a* to a value specific to instances of class B ?
};
4

4 に答える 4

9

できません。すべての派生クラスで共有される静的変数のインスタンスが1つあります。

于 2010-04-21T10:29:27.040 に答える
3

静的メンバーは、アプリケーション内で一意です。システムには単一のA::a定数があります。できることは、静的定数を非表示にするB::a静的定数を作成することです(完全修飾名を使用しない場合:BA::a

class A {
public:
   static const int a = 10;
};
static const int A::a;
class B : public A {
public:
   static const int a = 20;
   static void test();
};
static const int B::a;
void B::test() {
   std::cout << a << std::endl;    // 20: B::a hides A::a
   std::cout << A::a << std::endl; // 10: fully qualified
}
于 2010-04-21T10:35:15.073 に答える
3

これは、不思議なことに繰り返されるテンプレートパターンを使用して行うことができます(ただし、失う必要がありconstます)。

template <typename T>
class A {
public:
    static int a;
};

template <typename T>
int A<T>::a = 0;

class B : public A<B> {
    struct helper { // change the value for A<B>::a
        helper() { A<B>::a = 42; }
    };
    static helper h;
};
B::helper B::h;
于 2010-04-21T10:38:21.407 に答える
0

以下のようにこの方法を試すことができるかもしれません::以下の利点は、コードを複数回記述する必要がないことですが、実際に生成されるコードは大きくなる可能性があります。

#include <iostream>

using namespace std;
template <int t>
class Fighters {
protected :
    static const double Fattack;
    double Fhealth;
    static const double Fdamage;
    static int count;
public :
    Fighters(double Fh) : Fhealth(Fh) { }
    void FighterAttacked(double damage) {
        Fhealth -= damage;
    }
    double getHealth()
    {
        return Fhealth;
    }

    static int getCount() 
    {
        //cout << count << endl;
        return count;
    }
};

const double Fighters<1>::Fdamage = 200.0f;
const double Fighters<1>::Fattack = 0.6f;
int Fighters<1>::count = 0;

class Humans : public Fighters<1> {
public :
    Humans(double Fh = 250) : Fighters<1>(Fh) { count++; }
};

const double Fighters<2>::Fdamage = 40.0f;
const double Fighters<2>::Fattack = 0.4f;
int Fighters<2>::count = 0;

class Skeletons : public Fighters<2> {
public :
    Skeletons(double Fh = 50) : Fighters<2>(Fh) { count++; }
};

int main()
{

    Humans h[100];
    Skeletons s[300];

    cout << Humans::getCount() << endl;
    cout << Skeletons::getCount() << endl;

    return 0;
}

これは私の他のコード例の一部です..他の多くのデータを気にしないでください、しかし概念は見ることができます。

于 2016-06-18T14:04:07.093 に答える