【问题标题】:How to build a Constructor for a Vector of pointers to classes如何为类指针向量构建构造函数
【发布时间】:2013-01-16 20:40:41
【问题描述】:

我需要为类指针向量构建一个构造函数...

我的班级是:

class Song {

    string song_name;

    string auther_name;

    int popularity;

    SongStructure song_format;

    int song_length;

    int lengths[size];

    bool first_condition_true();

    bool second_condition_true(int index);

    }

};

我的向量是:

vector<Song*> play_list;

【问题讨论】:

  • 真正的问题是什么? std::vector 已经有一个构造函数,你不必创建那个。
  • 是的,你的问题是?

标签: c++ class pointers vector constructor


【解决方案1】:

随着新标准 C++11/0x 的引入,初始化列表已经被引入:

我假设您想创建一个 SongBook 类,其中包含一个歌曲指针向量和其他信息。 它们可以这样使用:

类文件:

class SongBook {
    vector<Song*> songlist;
    string name;

    // Constructor
    SongBook(std::initializer_list<Song*> songs) : songlist(songs) {}
}

然后像这样从你的 main 调用例如

SongBook book({new Song(...), new Song(...), new Song(...)});

【讨论】:

    【解决方案2】:

    您的向量有一个可以使用的有效构造函数。 (它为指针创建位置)。您所要求的可能是一种使指针指向某些有效Song 的方法。您将需要在某个循环中执行此操作(可能是 STL“循环”)。但你可能不需要那个,因为你的歌曲是合法可复制的!?。你可以使用vector&lt;Song&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多