zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    HDU1050
    POJ3528移石头
    CodeForces230A
    lca学习题
    rmq的st算法模板题 nyoj 119
    rmq问题和lca可以相互转化
    rmq算法,利用倍增思想
    poj 1274 基础二分最大匹配
    hdu 1520 树形dp入门题
    poj 1466 最大独立集
  • 原文地址:https://www.cnblogs.com/wxiaoli/p/4486001.html
Copyright © 2011-2022 走看看