ツリー内のすべてのクラスは、電圧と電流センサー(通常は1,2,3 ...という名前)を監視するための他のクラスとの関係に依存します。問題は、そこにあるセンサの数は、どのタイプのユニットがシミュレートされているかに依存します。派生クラスだけがそれを知っていることを意味します。クラス定義内に組み込みの配列を使用しますが、派生クラスに遅延されたサイズは隠蔽の原因になりますか?
#include <iostream>
class A {
public:
A() {};
virtual void Display() = 0;
protected:
int array[]; // size is purposefully left out in base class
};
class B : public A {
public:
B(int numbers[4]);
virtual void Display();
protected:
int array[4]; // 4 sensors are required, number fixed at compile time
}
B::B(int numbers[4]) {
for(int i=0; i<4; i++)
array[i] = numbers[i];
}
void B::Display() {
cout << " B numbers are: ";
for(int i = 0; i < 4; i++)
cout << array[i] << " ";
cout << endl;
}
class C : public A {
public:
C(int numbers[8]);
virtual void Display();
protected:
int array[8]; // 8 sensors needed, number fixed at compile time
};
C::C(int numbers[8]) {
for(int i=0; i<8; i++)
array[i] = numbers[i];
}
void C::Display() {
cout << " C numbers are: ";
for(int i = 0; i < 8; i++)
cout << array[i] << " ";
cout << endl;
}
このドライバは、G ++コンパイラを使用する場合、これは技術的に機能することを示しているが、私はBとCクラスの配列を再宣言することによって隠蔽データを有していてもよいことを恐れ。
main() {
int B_numbers[] = {1,2,,3,4};
int C_numbers[] = {5,6,7,8,9,10,11,12};
B b(B_numbers[]);
C c(C_numbers[]);
b.Display();
c.Display();
}
誰もが提供できるご提案ありがとうございます。
メンバーデータをオーバーライドすることはできません(独立した配列を作成しています)。 'int array [];'はサイズがゼロの配列です。テンプレートを見る時間。 – LogicStuff
あなたの最初の問題は、C++では長さがゼロの配列が許可されていないため、これは移植可能とは見なされないGCC拡張です。 –
基本クラス 'virtual int * Array()'に仮想関数を追加することを検討してください。派生クラスはその配列へのポインタを返します。 – kfsone