C++类的继承


#include <iostream>

class Box
{
public:
    // 构造函数
    Box(int h = 2, int w = 2, int len = 2);
    // 析构函数
    ~Box();
    int volume();

protected:
    int height, width, length;
};

Box::Box(int h, int w, int len)
{
    height = h;
    width = w;
    length = len;
}

Box::~Box()
{
    std::cout << "Destructor called." << std::endl;
}

int Box::volume()
{
    return height * width * length;
}

class BoxNew : public Box
{
public:
    BoxNew(int h = 2, int w = 2, int len = 2, int c = 2, int wh = 2) : Box(h, w, len)
    {
        color = c;
        weight = wh;
    }
    int volume()
    {
        return height * width * length * color * weight;
    }
    ~BoxNew() { std::cout << "BoxNew End;" << std::endl; }

private:
    int color, weight;
};

int main()
{
    BoxNew box1(1, 2, 3, 4, 5);
    std::cout << "box1's volume:" << box1.volume() << std::endl;
    return 0;
}