0

我有一个专辑类,旨在存储艺术家姓名(字符串)、专辑标题(字符串)和曲目对象列表(向量)。我正在尝试重载“<<”运算符以启用基于流的输出。

相关代码是这样的:

std::ostream& Album::printTracks (std::ostream &out, std::vector<Track> &t)
{
    unsigned int i;
    for (i=0; i<t.size(); i++)
        out << " " << t.at(i);
     return out;
}
std::ostream& operator<< (std::ostream &out, Album &a)
{
    out << "Artist name: " << a.artistName << "\n" <<
        "Album Title: " << a.albumTitle << "\n" <<
        "Tracks: " << a.printTracks(out,a.getTracks());
    return out;
}

应该按以下顺序打印:

  • 艺术家姓名
  • 专辑名称
  • 曲目列表

相反,当我给它测试数据时它会打印出来:

  • 曲目列表
  • 艺术家姓名
  • 专辑名称

“曲目:”后跟一个内存位置。

Constructor for "Track Class" is:
Track::Track (std::string t, Duration* d)
    {
        title = t;
        duration = d;
    }

在“track”类中重载“<<”的代码是:

std::ostream& operator<< (std::ostream &out, Track &t)
    {
    out << "Title: " << t.title << "\n" <<
        "Duration: " << *t.duration << "\n";
    return out;
    }

用于输出的最终代码是:

Duration* d = new Duration(3,4,50); //creating duration objects for testing
Duration* d2 = new Duration(5,7,300);
Duration* d4 = new Duration(3,3,50);
Track t1 = Track("Test",d); //creating track objects
Track t2 = Track("Test2",d2);
Track t3 = Track("Test3",d4);
std::vector<Track> tracks; //forming tracks into vector
tracks.push_back(t1);
tracks.push_back(t2);
tracks.push_back(t3);
Album a = Album("Test Artist","Test Album",tracks); //create album object
cout << a << endl; // output album object

想知道为什么订单没有按预期打印?

4

1 回答 1

5

未指定您的参数的评估顺序。其中一个具有副作用(打印轨道),因此如果首先评估它,您将首先看到打印的那些。

于 2012-12-13T01:19:43.000 回答