C++ find_if 另一个 class 的成员变量
C++ find_if member variable of another class
所以我有一个 class 叫做 Song,另一个 class 叫做 SongLibrary。
歌曲库仅包含一组所有歌曲和适当的方法。
我目前正在尝试制作一个功能来搜索歌曲库并检查歌曲是否具有特定标题。
我遇到的问题是歌曲库中的歌曲标题无法访问 class。
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;
}
我试图让该方法成为歌曲的朋友 class 但我不确定我是否理解它是如何工作的。
编辑
我使用以下
解决了问题
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 getter 像这样:
const std::string& getTitle() const { return m_title; }
在song
中添加一个"getter"函数,例如
class Song {
public:
const std::string& getTitle(){
return Title;
}
...
private:
...
std::string Title;
}
所以我有一个 class 叫做 Song,另一个 class 叫做 SongLibrary。 歌曲库仅包含一组所有歌曲和适当的方法。
我目前正在尝试制作一个功能来搜索歌曲库并检查歌曲是否具有特定标题。
我遇到的问题是歌曲库中的歌曲标题无法访问 class。
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;
}
我试图让该方法成为歌曲的朋友 class 但我不确定我是否理解它是如何工作的。
编辑 我使用以下
解决了问题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 getter 像这样:
const std::string& getTitle() const { return m_title; }
在song
中添加一个"getter"函数,例如
class Song {
public:
const std::string& getTitle(){
return Title;
}
...
private:
...
std::string Title;
}