//chapter7.10.cpp
/*定义一个Object类,有数据成员weight及其相应的操作函数,
由此派生出Box类,增加数据成员height和width及其相关1操作函数
声明一个Box类对象,观察构造函数与析构函数的调用顺序*/
#include <iostream>
#include "Classfile.h"
using namespace std;
int main()
{
int weight, height, width;
cin >> weight >> height >> width;
Box b(weight,height,width);
cout << b.getWeight()<<endl;
/*公有派生可以直接调用Object类的公有成员函数,
不需要在派生类重新声明同名的成员*/
cout << b.getHeight() << endl;
cout << b.getWidth() << endl;
cout << b.getV() << endl;
return 0;
}
//Classfile.h
#pragma once
#include <iostream>
using namespace std;
class Object {
private:
int weight;
public:
Object(int weight = 0);
int getWeight()const;
~Object();
};
class Box:public Object {
private:
int height;
int width;
public:
Box(int weight=0, int height=0, int width=0);
int getWeight()const;
int getHeight()const;
int getWidth()const;
int getV()const;
~Box();
};
//Classfile.cpp
#include <iostream>
#include "Classfile.h"
using namespace std;
Object::Object(int weight) :weight(weight)
{
cout << "calling the constructor of Object" << endl;
}
int Object::getWeight()const
{
return weight;
}
Object::~Object() { cout << "calling the desctructor of Object" << endl; }
Box::Box(int weight, int height, int width) :Object(weight), height(height), width(width)
{
cout << "calling the constructor of Box" << endl;
}
int Box::getHeight()const
{
return height;
}
int Box::getWidth()const
{
return width;
}
Box::~Box()
{
cout << "calling the destructor of Box" << endl;
}
int Box::getV()const
{
return Object::getWeight() * height * width;
}