简体   繁体   English

继承的类和父级的构造函数

[英]Inherited class and parent's constructor

#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();
}

When I compiled this program I got the follwing errors: 当我编译该程序时,出现以下错误:

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

I added a second constructor for ellipse as shown below (trial and error) and solved the issue 我为椭圆添加了第二个构造函数,如下所示(尝试和错误)并解决了该问题

ellipse() {

}

But I am not sure why the errors occurred before adding this. 但是我不确定为什么在添加此错误之前会发生错误。 Could anybody explain this to me? 有人可以向我解释吗?

In the constructor circle(float) , it needs to call the default constructor ellipse() with no arguments, because you did not provide any arguments in the "initialization list." 在构造函数circle(float) ,它需要不带任何参数的默认构造函数ellipse() ,因为您没有在“初始化列表”中提供任何参数。 To fix it, do this (and remove your ellipse() default constructor): 要解决此问题,请执行以下操作(并删除ellipse()默认构造函数):

circle(float r)
  : ellipse(r, r)
{
}

This simply delegates the initialization of a and b to the two-argument ellipse constructor. 这只是将ab的初始化委托给两个参数的ellipse构造函数。 It offers better encapsulation and more concise code. 它提供了更好的封装和更简洁的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM