zoukankan      html  css  js  c++  java
  • 将一个Student对象转换为Teacher对象

    // 7、定义Teacher类和Student类,将Student类转换成Teacher类
    #include<iostream>
    using namespace std;
    class Student; //提取引用申明
    class Teacher
    {
    private:
    int num;
    char *name;
    char *sex;
    public:
    Teacher()
    {
    num = 0;
    name = NULL;
    sex = NULL;
    }
    Teacher(int n, char *p, char *s)
    {
    num = n;
    name = p;
    sex = s;
    }
    Teacher(Student &s); //转换构造函数
    void display()
    {
    cout << "号码:" << num << endl;
    cout << "姓名:" << name << endl;
    cout << "性别:" << sex << endl;
    cout << endl;
    }
    };
    class Student
    {
    private:
    int num;
    char *name;
    char *sex;
    public:
    Student(int n, char *p, char *s)
    {
    num = n;
    name = p;
    sex = s;
    }
    friend Teacher; //将Teacher声明为Student的友元类,那么Teacher就可以访问Student的私有数据
    void display()
    {
    cout << "号码:" << num << endl;
    cout << "姓名:" << name << endl;
    cout << "性别:" << sex << endl;
    cout << endl;
    }
    };
    Teacher::Teacher(Student &s) //转换构造函数
    {
    num = s.num;
    name = s.name;
    sex = s.sex;
    }


    int main()
    {
    Student s1(1001,"chenliqiong","female");
    cout << "Student s1为:" << endl;
    s1.display();

    Teacher t1;
    t1 = Teacher(s1);
    cout << "移植后的Teacher t1为:" << endl;
    t1.display();
    return 0;
    }

    运行结果如下:

     

  • 相关阅读:
    c++作用域运算符---7
    REDIS类和方法说明
    netty WEBSOKET 客户端 JAVA
    出入库算法
    演讲的要义
    别人的面试经历
    在线表单生成器
    windows server 2012 安装 VC14(VC2015) 安装失败解决方案
    esxi 配置 交换主机 虚拟机交换机 linux centos 配置双网卡
    Linux下开发常用配置
  • 原文地址:https://www.cnblogs.com/liulijin/p/6411349.html
Copyright © 2011-2022 走看看