为什么以下代码
#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){}
构造函数的继承存在问题。我想在每次创建一个Rectangle或Triangle时调用Polygon的构造函数。但是,令我感到震惊的是,类Rectangle
和Triangle
非常相似,我只会为{ {1}}而不是Triangle
。你能否解释一下错误的原因以及我该如何解决?
答案 0 :(得分:1)
您的Triangle
班级
Trianlge(int width,int height): Polygon(width,height){}
^
^