c++ - 继承和构造函数

标签 c++ inheritance constructor

这不是家庭作业,只是我的 C++ 类(class)的一些训练练习,以便习惯继承和其他东西。所以练习的第一部分要求我们创建一个程序,它有一个类名 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 的值。有什么想法吗?

最佳答案

您忘记链接Square 的构造函数。您想将 Square 的构造函数更改为:

  Square(int w) : Rectangle(w,w) {}

关于c++ - 继承和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178771/

相关文章:

java - 创建一个对象并将其打印出来,但结果打印了引用。怎么解决这个问题呢?

c# - 在构造函数或析构函数中调用的虚函数的行为

c++ - 使用 *this 从右值进行预期的无效初始化

c++ - AdjustTokenPrivileges 错误 ERROR_NOT_ALL_ASSIGNED

c++ - 无法从其他类的函数访问对象的参数

c++ - 如何构建遗传算法类层次结构?

ios - Swift 中的通用类继承

c# - 如何让重载的构造函数同时调用默认构造函数和基构造函数的重载?

c++ - 在 MPI_Send/MPI_Recv 对中,如果没有正确同步,数据会丢失吗?

C++ 多继承顺序和虚函数