0

我遇到了朋友功能的问题。

我认为这是代码中唯一需要的部分。我的问题是这个函数。它说问题出在第一行,但我不知道这有多准确。

friend ostream & operator << (ostream & b, Book & a)
    {
    b.setf(ios::fixed | ios::showpoint);
    b.precision(2);
    b << "Title     :  \"" << a.title << "\"\n"
    << "Author      : \"" << a.author << "\"\n"
    << "Price       : $" << a.price / 100.0 << endl
    << "Genre       : " <<a.genre << endl
    << "In stock? " << (a.status ? "yes" : "no") << endl
    << endl;
    return b;
    }

我收到错误:lab10.cpp:95: error: can't initialize friend function âoperator<<â

lab10.cpp:95:错误:朋友声明不在类定义中

提前致谢

4

3 回答 3

1

你有在类中原型化的朋友函数吗?你需要在类中有一些东西表明这是一个友元函数。喜欢这条线

  friend ostream& operator<<(...);

或者其他的东西。查找重载插入/提取运算符的完整示例以获取更多信息。

于 2011-11-04T03:15:10.950 回答
1

您必须指定该函数是哪个类的朋友。您要么将该函数放在类声明中:

class Book{
...
  friend ostream & operator << (ostream & b, Book & a)
    {
    b.setf(ios::fixed | ios::showpoint);
    b.precision(2);
    b << "Title     :  \"" << a.title << "\"\n"
    << "Author      : \"" << a.author << "\"\n"
    << "Price       : $" << a.price / 100.0 << endl
    << "Genre       : " <<a.genre << endl
    << "In stock? " << (a.status ? "yes" : "no") << endl
    << endl;
    return b;
  }
};

另一种方法是在类中将其声明为朋友,并在其他地方定义它:

class Book{
...
    friend ostream & operator << (ostream & b, Book & a);
};

...

// Notice, there is no "friend" in definition!
ostream & operator << (ostream & b, Book & a)
    {
    b.setf(ios::fixed | ios::showpoint);
    b.precision(2);
    b << "Title     :  \"" << a.title << "\"\n"
    << "Author      : \"" << a.author << "\"\n"
    << "Price       : $" << a.price / 100.0 << endl
    << "Genre       : " <<a.genre << endl
    << "In stock? " << (a.status ? "yes" : "no") << endl
    << endl;
    return b;
}
于 2011-11-04T03:17:06.120 回答
0
于 2012-01-20T11:18:43.427 回答