2011-11-04 122 views
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:错误:无法初始化友元函数âoperator< <â

lab10.cpp:95:错误:友元声明不上课定义

在此先感谢

回答

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; 
} 
+0

这解决了我的问题。非常感谢您的投入。朋友的功能仍然让我感到困惑。 – user1028985

+0

请注意,只有通过ADL才能看到类体内定义的朋友函数。尽管如此,运营商无论如何都有望被使用。 –

1

您是否有在课堂内原型的朋友函数?你需要在课堂内有东西表明这是一个朋友功能。像线

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

什么的。查找一个完整的示例来重载插入/提取操作符以获取更多信息。

+0

我确实有过它的原型,但感谢您的回复。我忘了把它放在那里。 – user1028985

0
#include <iostream> 
#include <string> 
using namespace std; 

class Samp 
{ 
public: 
    int ID; 
    string strName; 
    friend std::ostream& operator<<(std::ostream &os, const Samp& obj); 
}; 
std::ostream& operator<<(std::ostream &os, const Samp& obj) 
    { 
     os << obj.ID<< “ ” << obj.strName; 
     return os; 
    } 

int main() 
{ 
    Samp obj, obj1; 
    obj.ID = 100; 
    obj.strName = "Hello"; 
    obj1=obj; 
    cout << obj <<endl<< obj1; 

} 

OUTPUT: 100你好 100 [小] ELLO 按任意键继续......

这可能是一个朋友的功能,只是因为对象是< <运营商和论证COUT的右边是在LHS。所以这个不能成为类的成员函数,它只能是一个朋友函数。