码迷,mamicode.com
首页 > 编程语言 > 详细

C++中对类的提前引用声明注意事项

时间:2015-05-07 21:43:23      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

//或许,友元是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; }

 

C++中对类的提前引用声明注意事项

标签:

原文地址:http://www.cnblogs.com/Wsally/p/4486001.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!