我有一個基類,從該基類派生的類,以及從派生類派生的另一個類。我的問題來自於使用構造函數來確定如何構建下一個類。C++繼承和類成員
這裏是使用繼承時遇到的問題的簡化版本。我是新來的C++。
基類:
class Grandfather
{
public:
Grandfather(int A, int B, int C) : a(A), b(B), c(C)
{}
virtual ~Grandfather();
virtual int getA();
virtual int getB();
virtual int getC();
private:
int a,b,c;
};
派生父類:
class Father : public Grandfather
{
public:
Father(int d);
virtual ~Father();
private:
int c; // i know this at compile time. How to define?
};
其中Father.cpp,構造的定義如下:
Father::Father(int d){
int a,b; //Father takes a parameter that then determines what a and b are
switch(d){
case 1:
a=2;
b=5
case 2:
a=6;
b=9;
default:
a=10;
b=2;
}
Grandfather(a,b,c); // where c is a known constant for this class
}
和派生,派生子類:
class Child : public Father
{
public:
Child() : Father(int d) // d is a known constant for this class
{}
virtual ~Child();
private:
int d; // how do i define d, if it is known at compile time?
};
因此,Child
在編譯時具有已知的整數值。當創建一個Child
對象時,它會自動調用帶有其變量的構造函數Father
。構造函數Father(in d)
查看從Child
傳入的變量,進行快速操作,然後調用已知的int c
的GrandFather構造函數和根據給出的int d
創建的另外兩個int a,b
。這顯然是不行的,因爲默認Grandfather()
構造函數自動調用
'enum {d = X};'在代碼註釋中回答您的問題。 – kfsone
相反,模板參數,可選'靜態constexpr int'成員。如果OP想用傳遞給構造函數的參數初始化它,太糟糕了,只能是'const int'。 – LogicStuff
修正'Child'構造函數中的錯別字。 – LogicStuff