2016-08-03 39 views
1

我遇到了一個問題,但我不知道我是否正確解決了問題,或者是否有更正確的方法。將const引用投射到派生

現在,我有兩個類(和從其他的一個繼承):

class Data_Base 
{ 
... 
} 

class Data_Error : public Data_Base 
{ 
... 
} 

現在,在相等運算的過載,我必須將常量引用轉換爲基礎對象派生再次對象,以便測試其成員。目前我在做這個:

bool Data_Error::operator==(const Data_Base &other) const 
{ 
    if (Data_Base::operator !=(other)) 
     return false; 

    const Data_Error &other_cast = (const Data_Error &)other; 

    ... More tests on other_cast ... 
} 

現在,有沒有可能性,在鑄造時刻other變量是別的東西比Data_Error,因爲Data_Base==運營商(和!=運營商,因爲它的實現作爲==的否定)也會檢查派生對象的類型,因此只有在類型正確的情況下才能到達該行。

現在,這有什麼問題嗎?有沒有更「正確」的解決方案?

我正在使用Qt(5.7),那麼是否有任何「更多QTish」解決方案?

+0

你爲什麼要比較'Data_Error'到'Data_Base'後代?它有什麼意義來比較層次結構中不同分支上的類型?只需堅持'bool Data_Error :: operator ==(const Data_Error&other)const',我說。 – StoryTeller

+0

@StoryTeller因爲當我有一個基本類型的列表,我想迭代它來檢查是否有一些項目是相等的。我只需在每個項目上調用==;在函數中我檢查類型是否相同,否則它們不相等。但是爲了這個目的,其他的類型應該是基本類型,否則程序不知道如何比較兩個不同的分支 – frarugi87

+0

你的'operator =='虛擬嗎?如果不是,它不會像你期望的那樣工作。 – StoryTeller

回答

1

應避免C型鑄件。你可以找到爲什麼here。您應該使用,而不是靜態澆鑄:

const Data_Error &other_cast = static_cast<const Data_Error &>(other); 

或動態施放檢查其他運行時有效類型Data_Error的

const Data_Error &other_cast = dynamic_cast<const Data_Error &>(other); 
+2

爲了這些目的,動態轉換更合適 – LmTinyToon

+0

我第一次添加它,但不確定引用的行爲。但是你是對的,我讀了它 – wasthishelpful

+0

所以'dynamic_cast'解決方案更好?如果是這樣,如果演員失敗怎麼辦?它是否拋出異常或將'other_cast'設置爲'nullptr'? – frarugi87

1

正確的方法是對指針使用dynamic_cast,因爲它根本如果對象不是正確的派生類型,則返回null。你的例子會變成:

bool Data_Error::operator==(const Data_Base &other) const 
{ 
    if (Data_Base::operator !=(other)) 
     return false; 

    const Data_Error *other_cast = dynamic_cast<const Data_Error *>(&other); 
    if (other_cast == nullptr) { // not the correct type 
     return false; 
    } 

    ... More tests on *other_cast ... 
} 
+0

這是否會影響其他的「恆常」? – frarugi87

+0

爲什麼你會用這個dynamic_cast?如果你已經知道這個類型,你可以static_cast它。 「在施法時刻其他變量不可能是Data_Error之外的其他變量」 – xaxxon

+0

@ frarugi87:no,這會將const ref轉換爲指向const的指針。所以* constness *在這裏被保存。 –