C++中对类的提前引用声明注意事项
//或许,友元是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; }