C++ find_if另一个类的成员变量

C++ find_if member variable of another class

本文关键字:成员 变量 另一个 find if C++      更新时间:2023-10-16

所以我有一个名为Song的类,另一个名为SongLibrary的类。歌曲库仅包含一组所有歌曲和适当的方法。

我目前正在尝试制作一个功能来搜索歌曲库并检查歌曲是否具有特定标题。

我遇到的问题是歌曲库类无法访问歌曲标题。

m_songs是我在歌曲库中用来存储所有歌曲的集合的名称。

m_title 是 Song 中标题的成员变量.cpp

在歌曲库中.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;
}

试图让该方法成为歌曲类的朋友,但我不确定我是否理解它是如何工作的。

编辑我使用以下方法解决了问题

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的朋友。但我建议你像这样为你的歌名做一个公开的获取者:

const std::string& getTitle() const { return m_title; }

song中添加一个"getter"函数,例如

class Song {
    public: 
       const std::string& getTitle(){
           return Title;
       }
       ...
    private:
       ...
       std::string Title;
}