C++中对类的提前引用声明注意事项
2024-09-07 06:13:51
//或许,友元是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=):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=):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=;
} //重载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(,"xiaoer",'F',);
cout<<s;
Teacher t=Teacher(s);
cout<<t;
return ;
}
最新文章
- C#中关于异步的三种写法
- ES(一): 架构及原理
- hdu3594 强连通(仙人掌图)
- centos 6安装redis 2.8.19
- AX函数,将EXCEL列号转为列名
- java 中 java.lang.ArrayIndexOutOfBoundsException: 0 异常
- cookingk配置项中的chunk:true含义
- Linux企业级项目实践之网络爬虫(12)——处理HTTP应答头
- 线程异常:undefined reference to &;#39;pthread_create&;#39; 处理
- Jquery对raido的一些操作方法
- 《Language Implementation Patterns》之 增强解析模式
- mysql安装及常见问题
- Nginx 请求的11个阶段
- Confluence 6 在升级过程中查看合并日志
- RabbitMQ在java中基础使用
- docker安装mongodb并备份
- Android 开发 系统组件集合
- java中哪些数值不能被初始化
- PS插件CameraRaw-初次尝试
- PersistentAliasAttribute &; CalculatedAttribute &; CalculatedPersistentAliasAttribute
热门文章
- UITableViewCell -- 动画
- 基于HTML5的PACS--HTML5图像处理
- C# 通过WebService方式 IIS发布网站 上传文件到服务器[转]
- 使用cacheBuilder实现函数防抖
- wince开发_摩托罗拉MC3100_打开条码设置
- java中自带时间类使用方法实例 Date,Timestamp,DateFormat
- 无法安装 golang.org/x/tools/的库
- Adam:大规模分布式机器学习框架
- php实现类似淘宝最近浏览商品的功能模型代码
- 爬虫框架_scrapy1