继承和构造函数

问题描述

| 这不是家庭作业,只是我的C ++类的一些培训练习,目的是习惯于继承和学习东西。因此,练习的第一部分要求我们创建一个名为Rectangle的类的程序,并应该执行构造函数的getter和setter的操作,并找到面积和周长。练习的第二部分说要创建一个新的类名称Square,该类扩展了Rectangle并具有一个构造函数,该构造函数的参数将为正方形的宽度。然后程序应打印区域和周长。
#include <iostream>
using namespace std;

class Rectangular {

    private:
        int width;
        int height;

    public:

        Rectangular () {
            width = 5;
            height = 5;
        }

        Rectangular (int w,int h) {
            width = w;
            height = h;
        }

        void setWidth (int w) {
            width = w;
        }

        void setHeight (int h) {
            height = h;
        }

        int getWidth () {
            return width;
        }

        int getHeight () {
            return height;
        }

        int getArea () {
            return width*height;
        }

        int getPerimeter () {
            return width+height;
        }
 };

class Square : public Rectangular{
    public:
        Square (int w) {
           getWidth();
        }
};

int main(int argc,char *argv[])
{
    Rectangular a,b(10,12);
    Square c(5);
    cout << \"Width for a: \" << a.getArea() << \" Perimeter for a: \" << a.getPerimeter() << endl;
    cout << \"Width for b: \" << b.getArea() << \" Perimeter for b: \" << b.getPerimeter() << endl;
    cout << \"Area for c: \" << c.getArea() << \" Perimeter for c: \" << c.getPerimeter() << endl;
 }
程序打印出来
Width for a: 25 Perimeter for a: 10
Width for b: 120 Perimeter for b: 22
Area for c: 25 Perimeter for c: 10
出于某种原因,c获得a的值。有什么想法吗?     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)