2013-01-18 50 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