1
爲什麼下面的代碼C++構造繼承錯誤
#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){}
它與構造函數的繼承問題。每次創建矩形或三角形時,我都想調用Polygon的構造函數。但是,我發現類Rectangle
和Triangle
非常相似,我只在Triangle
上出錯,而在Rectangle
上出錯。您能否向我解釋錯誤的原因以及如何解決?
拼字/錯字也許是:'Trianlge'與'Triangle'? –
你拼錯'三角形'。 –
...並使用初始化列表 –