码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 多继承

时间:2019-11-16 23:25:18      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:virt   main   ace   rtu   cst   pre   protect   out   cte   

构造函数,先执行父类的构造函数依次执行,销毁对象,是按照初识化构造函数顺序,倒叙执行。

#include <iostream>
#include <cstdlib>

using namespace std;


//.h 声明
class Person {
public:
    void play();

    Person(string name = "kitty");

    virtual ~Person();

protected:
    string m_strName;
};

class Soldier : public Person {
public:
    Soldier(string name = "james", int age = 20);

    void work();

    virtual ~Soldier();

protected:
    int m_iAge;
};

class Infantry : public Soldier {
public:
    Infantry(string name = "jack", int age = 30);

    void attack();

    virtual ~Infantry();
};

//cpp  这叫定义
void Person::play() {
    cout << "Person::play()" << endl;
    cout << m_strName << endl;

}

Person::~Person() {
    cout << "~Person()" << endl;
}

Person::Person(string name) {
    m_strName = name;
    cout << "Person()" << endl;
}

Soldier::Soldier(string name, int age) {
    m_strName = name;
    m_iAge = age;
    cout << "Soldier()" << endl;
}

Soldier::~Soldier() {
    cout << "~Soldier()" << endl;
}

void Soldier::work() {
    cout << m_strName << endl;
    cout << m_iAge << endl;
    cout << "Soldier::work()" << endl;
}

Infantry::Infantry(string name, int age) {
    m_strName = name;
    m_iAge = age;
    cout << "Infantry()" << endl;
}

Infantry::~Infantry() {
    cout << "~Infantry()" << endl;
}

void Infantry::attack() {
    cout << m_strName << endl;
    cout << m_iAge << endl;
    cout << "Infantry::attack()" << endl;
}

void test1(Person p) {
    p.play();
}

void test2(Person &p) {
    p.play();
}

void test3(Person *p) {
    p->play();
}

int main() {
    Infantry infantry;
    test1(infantry);
    test2(infantry);
    test3(&infantry);
    return 0;
}

C++ 多继承

标签:virt   main   ace   rtu   cst   pre   protect   out   cte   

原文地址:https://www.cnblogs.com/wuyanzu/p/11874320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!