C++构造函数继承错误

标签 c++ constructor

<分区>

为什么会出现下面的代码

#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
    Polygon()
    {
             cout<<"Constructor with no arguments\n";
             width = 0;
             height = 0;
    }
    Polygon(int width,int height)
    {
                cout<<"Constructor with 2 arguments\n";
                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){}

是构造函数的继承问题。每次创建矩形或三角形时,我都想调用多边形的构造函数。但是,令我震惊的是类 RectangleTriangle 非常相似,并且我只得到 Triangle 的错误,Rectangle 没有。你能解释一下错误的原因吗?我该如何解决?

最佳答案

你的 Triangle 类中有一个拼写错误

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

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

相关文章:

inheritance - 派生类的大括号(无构造函数)初始化

java - 当我正确查看未定义的方法(构造函数)时,出现有关未定义方法(构造函数)的错误? ( java )

继承构造函数的 C++ 可见性

java - 如何从构造函数返回具有预设字段的新实例

c++ - 从祖先的方法和构造函数调用后代的方法

c++ - 连接多个字符

c# - MAKEWORD c++ Windows 宏的 C# 等价物是什么?

c++ - 如何部署依赖动态库的应用程序?

c++ - 为什么我的 glutWireCube 没有放在原点?

c++ - 访问嵌套类的成员