所以我有一个名为 Song 的类,还有一个名为 SongLibrary 的类。 歌曲库仅包含一组所有歌曲和适当的方法。
我目前正在尝试制作一个搜索歌曲库并检查歌曲是否具有特定标题的功能。
我遇到的问题是歌曲库类无法访问歌曲标题。
m_songs 是我在歌曲库中用来存储所有歌曲的集合的名称。
m_title是Song.cpp中title的成员变量
在 SongLibrary.cpp 中
bool SongLibrary::SearchSong(string title)
{
bool found = false;
std::find_if(begin(m_songs), end(m_songs),
[&](Song const& p)
{
if (p.m_title == title) // error here (m_title is inaccessible)
{
found = true;
}
});
return found;
}
我试图使该方法成为 song 类的 friend ,但我不确定我是否理解它是如何工作的。
编辑 我使用以下解决了问题
bool SongLibrary::SearchSong(string title)
{
if (find_if(begin(m_songs), end(m_songs),[&](Song const& p)
{return p.getTitle() == title;}) != end(m_songs))
{
return true;
}
return false;
}
最佳答案
如果你想使用友元类,你应该让SongLibrary
成为Song
的友元类。但我建议你像这样为你的歌曲标题做一个公共(public) setter/getter :
const std::string& getTitle() const { return m_title; }
关于C++ find_if 另一个类的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139660/