#include<iostream>
#define PI 3.14
using namespace std;
class ellipse
{
protected:
float a,b;
public:
ellipse(float x, float y)
{
a=x;
b=y;
}
float area()
{
return (PI*a*b);
}
};
class circle : public ellipse
{
public:
circle(float r)
{
a=r;
b=r;
}
};
main() {
float x,y,r;
cout<<"Enter the two axes of the ellipse (eg. 5 4) : ";
cin>>x>>y;
cout<<"\nEnter the radius of the circle : ";
cin>>r;
ellipse obj(x,y);
cout<<"\nEllipse Area : "<<obj.area();
circle obj1(r);
cout<<"\nCircle Area : "<<obj1.area();
}
当我编译这个程序时,我得到了以下错误:
friendclass4.cpp: In constructor ‘circle::circle(float)’:
friendclass4.cpp:24:1: error: no matching function for call to ‘ellipse::ellipse()’
friendclass4.cpp:24:1: note: candidates are:
friendclass4.cpp:10:1: note: ellipse::ellipse(float, float)
friendclass4.cpp:10:1: note: candidate expects 2 arguments, 0 provided
friendclass4.cpp:5:7: note: ellipse::ellipse(const ellipse&)
friendclass4.cpp:5:7: note: candidate expects 1 argument, 0 provided
我为椭圆添加了第二个构造函数,如下所示(试错)并解决了问题
ellipse() {
}
但我不确定为什么在添加此错误之前发生错误。 有人可以向我解释一下吗?
答案 0 :(得分:3)
在构造函数circle(float)
中,它需要调用没有参数的默认构造函数ellipse()
,因为您没有在“初始化列表”中提供任何参数。要解决此问题,请执行此操作(并删除ellipse()
默认构造函数):
circle(float r)
: ellipse(r, r)
{
}
这只是将a
和b
的初始化委托给双参数ellipse
构造函数。它提供了更好的封装和更简洁的代码。