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

本文通过一个具体的示例展示了如何在C++中使用友元类及构造函数,并讨论了在不同编译环境下可能出现的问题。文章重点介绍了如何从一个类构造另一个类的对象,并实现了两个类之间的数据共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/wxiaoli/p/4486001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值