//或許,友元是VC++6.0心里永遠的痛,對於這個BUG我一直很介意。
//注:這個程序在VC++6.0里是行不通的,在VS2008里是可以的。
#include <iostream>
#include <string>
using namespace std;
class Student; //提前引用聲明
//聲明Teacher類
class Teacher {
public:
Teacher(){}
Teacher(int i,string s,char c,int t=0):num(i),name(s),sex(c),theachYears(t){}
Teacher(Student);
friend ostream& operator<<(ostream& out,Teacher& te);
private:
int num;
string name;
char sex;//F/M
int theachYears;
};
//聲明Student類
class Student {
public:
Student(){}
Student(int i,string s,char c,int g=0):num(i),name(s),sex(c),grade(g){}
friend Teacher::Teacher(Student);
friend ostream& operator<<(ostream& out,Student& st);
private:
int num;
string name;
char sex;//F/M
int grade;
};
//注意:根據慣例,我們喜歡在類的聲明前直接寫成員函數的實現;
//但是,該構造函數的實現不能寫在Student類聲明之前,
//因為它使用了Student類的成員,提前引用聲明在這里將不起作用
Teacher::Teacher(Student st)
{
num=st.num;
name=st.name;
sex=st.sex;
theachYears=0;
}
//重載Teacher類的<<
// 注意:該構造函數的實現不能寫在Student類聲明之前,原因同上
ostream& operator<<(ostream& out,Teacher& te)
{
out<<"num="<<te.num<<","<<"name="<<te.name<<","<<"sex="<<te.sex<<","<<"theachYears="<<te.theachYears<<endl;
return out;
}
//重載Student類的<<
ostream& operator<<(ostream& out,Student& st)
{
out<<"num="<<st.num<<","<<"name="<<st.name<<","<<"sex="<<st.sex<<","<<"grade="<<st.grade<<endl;
return out;
}
int main()
{
Student s(1,"xiaoer",'F',2);
cout<<s;
Teacher t=Teacher(s);
cout<<t;
return 0;
}