C++:结构内的成员功能

C++: member function within structures

本文关键字:成员 功能 结构 C++      更新时间:2023-10-16

所以我有一个结构,它接受四个不同参数(名称、艺术家、大小和添加日期)的条目,但是我还有另一个结构,它本质上是条目结构的库,我想在库结构中创建一个插入成员函数,该函数接受一个参数,该参数是要放置在库中的条目。

在标题中

struct MusicEntry{
    string name, artist, date_added;
    long size;
    MusicEntry() = default;
    MusicEntry(string name_str, string artist_str, long size_int, string date_added_str) : 
    name(name_str), artist(artist_str), size(size_int), date_added(date_added_str) {};
    MusicEntry to_string();
};
struct MusicLibrary{
    MusicLibrary(string) {};
    MusicLibrary to_string();
    MusicEntry insert(); //not sure how this should be passed with MusicEntry
};

在功能中

.cpp
MusicEntry MusicLibrary::insert(){
     //some code
}

每首歌曲都提供了一个唯一的ID,这就是通过插入成员函数传递

的基本内容。

我假设您希望 MusicLibrary 包含 MusicEntry 的所有实例,因此您应该查看通用容器,例如 std::vector。

http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTOR

将 MusicEntry 传递到音乐库中应使用引用 (&) 或指针 (*) 来完成。

MusicEntry* MusicLibrary::insert(const MusicEntry* myEntry){
     //some code
}

MusicEntry& MusicLibrary::insert(const MusicEntry& myEntry){
     //some code
}