C++_day7_继承

#include <iostream>

using namespace std;

class Human{
public:
    Human(string const& name, int age):m_name(name), m_age(age)
    {
        cout << "Human构造:" << this << endl;
    }
    ~Human(void)
    {
        cout << "Human析构:"<< this << endl;
    }
    void eat(string const& food)
    {
        cout << "I am eating " << food << '.' << endl;
    }
    void sleep(string const& loc)
    {
        cout << "I am sleepping at " << loc << endl;
    }
    void who(void)
    {
        cout << "My name is " << m_name << ", I'm " << m_age << " years old." << endl;
    }
    string m_name;
    int m_age;
};

class Student: public Human{
public:
    Student(string const& name, int age, int no):Human(name, age), m_no(no)
    {
        cout << "Student构造:" << this << ' ' << &m_no << endl;
    }
    ~Student(void)
    {
        cout << "Student析构:"<< this << endl;
    }
    void learn(string const& course)
    {
        cout << "I am a student, My no is " << m_no << ", I am learning " << course << '.' << endl;
    }
    int m_no;
private:
    int m_a;
protected:
    int m_c; //子类可以访问
};

class Teacher: public Human{
public:
    Teacher(string const& name, int age, float salary):Human(name, age), m_salary(salary)
    {
        cout << "Teacher构造:" << this <<' ' << &m_salary << endl;
    }
    ~Teacher(void)
    {
        cout << "Teacher析构:"<< this << endl;
    }
    void teach (string const& course)
    {
        cout << "I am a teacher, My salary is " << m_salary << ", I'm teaching " << course << '.' << endl;
    }
    float m_salary;
};

int main(void)
{
    Student s1("WJ Zhang", 25, 1001);
    cout << s1.m_name << endl;
    cout << s1.m_age << endl;
    cout << s1.m_no << endl;
    s1.who();
    s1.eat("noodle");
    s1.sleep("floor");
    s1.learn("C++");
    
    Teacher t1("SF Zhang", 90, 20000);
    cout << t1.m_name << endl;
    cout << t1.m_age << endl;
    cout << t1.m_salary << endl;
    t1.who();
    t1.eat("chicken");
    t1.sleep("sofa");
    t1.teach("C++");    
    cout << sizeof(Human) << endl;
    cout << sizeof(Student) << endl;
    cout << sizeof(Teacher) << endl;
    cout << sizeof(string) << endl;
    Human* ph = &s1;    //is a ...
    cout << ph->m_name << endl;
    cout << ph->m_age << endl;
    //cout << ph->m_no << endl;    //error: ‘class Human’ has no member named ‘m_no’
    ph->who();
    Student* ps = static_cast<Student*>(ph);
    cout <<ps->m_no << endl;
    /*导致风险
    Human h1("ZR Zhou", 18);
    ps = static_cast<Student*> (&h1);
    cout << ps->m_no << endl;
    ps->learn("123");  
    */
    
    /*谨慎慎用对象截切
    Human h1 = s1;
    cout << h1.m_name << endl;
    cout << h1.m_age << endl;
    */
    
    return 0;
}

 

 

 

posted @ 2019-04-09 13:21  鸿蒙过客  阅读(140)  评论(0编辑  收藏  举报