C++构造函数继承错误

C++ constructor inheritance error

本文关键字:错误 继承 构造函数 C++      更新时间:2023-10-16

为什么以下代码是

#include <iostream>
using namespace std;
class Polygon {
  protected:
    int width, height;
    Polygon()
    {
             cout<<"Constructor with no argumentsn";
             width = 0;
             height = 0;
    }
    Polygon(int width,int height)
    {
                cout<<"Constructor with 2 argumentsn";
                this->width = width;
                this->height = height;
    }
 };
class Rectangle: public Polygon {
  public:
         Rectangle(int width,int height):Polygon(width,height){}
    int area ()
      { return width * height; }
 };
class Triangle: public Polygon {
  public:
         Trianlge(int width,int height): Polygon(width,height){}
    int area ()
      { return width * height / 2; }
  };
int main () {
  //Rectangle rect(4,4);
  //Triangle trgl(4,4);
  return 0;
}

导致这些错误:

 test.cpp:34:39: error: ISO C++ forbids declaration of ‘Trianlge’ with no type [-fpermissive]
          Trianlge(int width,int height): Polygon(width,height){}
                                       ^
test.cpp: In member function ‘int Triangle::Trianlge(int, int)’:
test.cpp:34:42: error: only constructors take member initializers
          Trianlge(int width,int height): Polygon(width,height){}
                                          ^
test.cpp:34:64: warning: no return statement in function returning non-void [-Wreturn-type]
          Trianlge(int width,int height): Polygon(width,height){}

这是构造函数的继承问题。每次创建矩形或三角形时,我都想调用Polygon的构造函数。然而,让我震惊的是,类RectangleTriangle非常相似,并且我只在Triangle中出错,而在Rectangle中没有。你能给我解释一下出错的原因吗?我该怎么修?

您的Triangle类中有一个打字错误

Trianlge(int width,int height): Polygon(width,height){}
   ^
   ^