2013-03-13 100 views
0

在基類的非虛函數中調用派生類中實現的基類的虛函數是否正確?類似於在基類的非虛函數中調用基類的虛函數

class A 
{ 
virtual void func1() = 0; 

void func2() 
{ 
    func1(); 
} 
}; 

class B : public A 
{ 
virtual void func1() 
{ 
    //do something here; 
} 
}; 

int main() 
{ 
A* obj = new B; 
obj->func2(); 
return 0; 
} 

回答

1

是的。當您需要操作符實現的虛擬函數行爲時使用此技術:您可以使用虛擬(或抽象)函數來定義操作符,並讓專業化來決定如何實現該函數。

例如:

class base 
{ 
// yada yada yada 
    base& operator=(const base& other) { return assign(other); } 
protected: 
    virtual base& assign(const base& other) = 0; // specializations will decide 
               // what assignment means 
}; 

編輯:另一個使用了該技術,讓您的類的特例來控制更復雜的操作只有部分:

class database 
{ 
public: 
    void execute(const std::string& query) 
    { 
     begin_transaction(); // in practice, this should be RAII 
     connection_.execute(query); 
     end_transaction(); 
    } 
protected: 
    virtual void begin_transaction() = 0; 
    virtual void end_transaction() = 0; 
private: 
    whatever &connection_; 
}; 

在數據庫中特,一假設mysql_database::begin_transaction將具有與sqlite_database::begin_transaction不同的實現。

2

是的,這將起作用。你自己嘗試過嗎?

+2

+1。當然,有時候「嘗試它」會導致諸如「y = x ++ + x ++」這樣的事情 - 它會「有效」,但不會「每次都正確運行」。所以只是因爲某些方法有效,並不意味着它是可以接受的,甚至是對的。 – 2013-03-13 17:37:57

1

是的,沒關係。這允許您在基類中提供通用流程,其細節專門針對其子項。

請參閱template method

+0

好的,謝謝:)。我正在嘗試func1中的一些複雜的東西,它給我鏈接器錯誤,我認爲這是由於實現錯誤:) – raveesh 2013-03-13 17:36:20

2

不僅它是一種衆所周知的工作方式來解決事情,但如果內聯func2,這可能意味着沒有額外的開銷,而不是直接調用內部函數。顯然,有時整個目的是在func1內部做一些事情,然後在中間或最後調用func2,但是在額外工作量很小的情況下,「額外功能層」可能完全消失。

相關問題