2013-01-18 48 views
0
SongPart mtm::SongStructure::getPart(int index) const { 
    assert(index >= 0 && index < num_of_parts); 
    return song_parts[index]; 
} 

const SongPart& mtm::Song::operator[](int index) const { 
    assert(index >= 0 && index < song_length); 
    return (song_format->getPart(index)); 
} 

我得到的第二個函數從返回值這樣的警告:返回參照臨時C++

返回參考臨時[默認啓用]

如何解決這一問題?而且我不能改變每個函數的返回值!

+1

你確實是需要改變getPart揭露,如果參考你想通過引用將它從SongPart :: operator []傳遞出去。 –

+2

'getPart'應該可能返回'SongPart const&' –

+1

您已排除正確的修復。爲了提供不同的修復,請告訴我們更多關於爲什麼您不能更改每個功能的返回值。 –

回答

2

改變所述第一函數爲:

const SongPart& mtm::SongStructure::getPart(int index) const { 
    assert(index >= 0 && index < num_of_parts); 
    return song_parts[index]; 
} 

的原因是調用由返回值song_format->getPart(index),從而創建第二函數的堆棧上的本地。如果你返回一個參考吧,第二個函數返回後,轟....

4

你得到的警告,因爲getPart返回複製的song_parts[index]。如果它返回參考song_parts[index],那麼你的代碼將是正確的。

所以,你需要的getPart返回類型更改爲SongPart const&

SongPart const & mtm::SongStructure::getPart(int index) const { 
    assert(index >= 0 && index < num_of_parts); 
    return song_parts[index]; 
} 

const是必要的,因爲函數是const成員函數。

爲什麼在operator[]中使用assert時,當您將呼叫轉發到getPart時,仍然會發出斷言?只需寫下:

const SongPart& mtm::Song::operator[](int index) const { 
    //assert(index >= 0 && index < song_length); not needed! 
    return (song_format->getPart(index)); 
} 

當不需要時避免額外的邊界檢查。

1

如果您無法更改返回類型getPart(),那麼您無法有效地調用它。讓我們考慮如何在不調用getPart()的情況下訪問數據。

解決方法1:調用一些其他功能:

const SongPart& mtm::SongStructure::getPartReference(int index) const { 
    assert(index >= 0 && index < num_of_parts); 
    return song_parts[index]; 
} 

const SongPart& mtm::Song::operator[](int index) const { 
    assert(index >= 0 && index < song_length); 
    return (song_format->getPartReference(index)); 
} 

解決方案2:直接從operator[]返回song_parts[index]

const SongPart& mtm::Song::operator[](int index) const { 
    assert(index >= 0 && index < song_length); 
    return (song_format->song_parts[index]); 
} 
+0

如果'song_parts'是'private'(它應該是)怎麼辦?請注意,'Song'和'SongStructure'是兩個不同的類,'song_parts'是'SongStructure'的成員。 – Nawaz

+0

然後,在解決方案#2中,他需要將一個朋友聲明添加到'SongStructure'中,或者將其從'private'改爲'public'。 –

+0

這兩個都是壞主意,在我看來。 – Nawaz