我遇到以下問題:使用庫(它是hdf5庫,但沒關係)。
我想做類似以下的事情,但我認爲我不能,因爲基類是抽象的。換句話說,我不能遲到綁定,因爲我不能實例化一個抽象類的對象。如何避免無法實例化抽象類的問題
我有一個抽象類和2個派生類。 main()的代碼不正確,因爲我不能執行Base theObject;
//An abstract class
class Base
{
protected:
Base() {}
public:
void doSomething() = 0;
};
class DerivedA : public Base
{
public:
DerivedA() : Base() {}
void doSomething() {cout << "I am a DerivedA" << endl;}
};
class DerivedB : public Base
{
public:
DerivedB() : Base() {}
void doSomething() {cout << "I am a DerivedB" << endl;}
};
int main()
{
// A special function returns the type of object that it is placed at "thePath".
int theType = someSpecialFunction(thePath);
Base theObject; //This is not possible.
switch (theType)
{
case 1: //A derivedA object
{
theObject = openObjectOfTypeA(thePath); //Special function of the library.
break;
}
case 2: //A derivedB object
{
theObject = openObjectOfTypeB(thePath); //Special function of the library
break;
}
}
theObject.doSomething();
//whatever
}
我可以做類似以下的事情。但是,在真實場景中,我會以很多重複的代碼結束。
int main()
{
// A special function returns the type of object that it is placed at "thePath"
int theType = someSpecialFunction(thePath);
switch (theType)
{
case 1: //A derivedA object
{
DerivedA theObject = openObjectOfTypeA(thePath);
theObject.doSomething();
break;
}
case 2: //A derivedB object
{
DerivedB theObject = openObjectOfTypeB(thePath);
theObject.doSomething();
break;
}
}
//whatever
}
有沒有什麼方法可以避免我的「解決方案」? 預先感謝您。
你不能有實例,但你可以有指針,你可以使用'Base * theObject'。無論如何,由於對象切片,Base theObject = DerivedA();被打斷(與Base的抽象無關) – user463035818
語言提供了多態性,因此您不必在類型和向下轉換時進行調度。 –
@ tobi303關於對象切片問題。如果我僅使用Base * theObject指針調用doSomething(),那麼沒有問題嗎? –