C++——定义一动物类私有数据成员:年龄、体重,成员函数:构造函数、析构函数、输出函数),再由此派生出狗类 ,定义一个 类的对象,观察基类与派生类的构造函数和析构函数的调用顺序。

没注释的源代码

#include <iostream>

#include <string>

using namespace std;

class Animal

{

public:

    Animal(int a,double w):age(a),weight(w){cout<<"Constructor in Animal."<<endl;}

    ~Animal(){cout<<"Constructor in Animal."<<endl;}

    void display()

    {

        cout<<"age:"<<age<<endl;

        cout<<"weight:"<<weight<<endl;

    }

private:

    int age;

    double weight;

};

class Dog:public Animal

{

public:

    Dog(int a,double w,string col):Animal(a,w),color(col){cout<<"Constructor in Dog."<<endl;}

    ~Dog(){cout<<"Constructor in Dog."<<endl;}

    void display1()

    {

        display();

        cout<<"color:"<<color<<endl;

    }

private:

    string color;

};

int main()

{

    Dog d(5,10,"白色");

    d.display1();

    return 0;

}

猜你喜欢

转载自blog.csdn.net/2303_80770781/article/details/143094048