关于友元在类外定义还是在类内定义的问题
昨天看到论坛里一篇关于重载operator <<的帖子,我试了下,有一个问题不明白,以前倒没注意过,代码如下请各位看一下:
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
int key;
string name;
friend ostream & operator << (ostream &s,const student &k)
{
cout << "in";
return s;
}
friend void ff(student &s)
{
cout<<s.name<<endl;
};
student(){};
virtual ~student(){};
student(string &s);
};
student::student(string &s)
{
name=s;
}
ostream & operator << (ostream &s,const student &k)
{
cout<<"out";
//printf("name=%s,key=%d\n", k.name, k.key);
//printf("name=%s,key=%d\n", "k.name", 1);
return s;
}
void ff(student &s)
{
cout<<"out"<<endl;
}
void main()
{
string t="tim";
const student s1(t);
cout<<s1<<endl;
}
出现两个错误,一个是说函数ff已经有定义了,另一个是说operator<< is ambiguous,两个函数都是友元函数,怎么会有上面两个不同的错误? 我把类外面的operator<<参数去掉const就会少一个错误了,这应该是函数解析对了,但为什么函数ff没有出现类似的问题呢?而是说已经定义过了呢?是不是友元函数实现应该放在类定义之内?