【问题标题】:How to access Constructor of Parent class in C++ with parent class having a pure virtual function如何使用具有纯虚函数的父类在 C++ 中访问父类的构造函数
【发布时间】:2016-04-15 19:09:24
【问题描述】:

我正在尝试从类形状创建圆形和矩形。如果我使用参数(来自圆形类)调用 Shape() 构造函数,我希望为 y 分配 pi。由于 Shape 具有纯虚函数,因此编译器显示错误。我该如何克服这个错误。那么为什么默认参数运行正确呢? 我也从 Circle 类中尝试了 this->Shape(0) 。编译器说“无效使用”

#include<iostream>
using namespace std;

class Shape
{public:
double x,y;

   Shape()
   {x=0;y=0;}

   Shape(int p,int t=3.14159)
   {x=p;y=t;}

   virtual void display_area()=0;
   virtual void get_data()=0;
};



class Circle: public Shape
{public:

    Circle()
    {Shape(0);}    //ERROR HERE

    void get_data()
    {cout<<"\nRadius: ";cin>>x;}

    void display_area()
    {cout<<"\nArea: "<<y*x*x;}
};

【问题讨论】:

  • 难怪如果代码格式如此糟糕,您无法修复代码。规则 #1:正确格式化您的代码!
  • 为什么你的代码格式这么差?你怎么能读到这个?

标签: c++ inheritance constructor virtual-functions


【解决方案1】:

基类总是在构造函数的块运行之前初始化,所以你在构造函数的member initialization list..中进行初始化。

我还修复了您代码中的另一个错误....您正在进行一些缩小转换,这不会按您的意愿工作...

#include<iostream>
using namespace std;

class Shape
{
public:
    double x,y;

Shape()
{  
     x=0;
     y=0;
}

Shape(double p, double t=3.14159)   //changed from Shape(int p, int t=3.14159)
{  
     x=p;
     y=t;
}

virtual void display_area()=0;

virtual void get_data()=0;
};

class Circle: public Shape
{
public:
    Circle() : Shape(0)
{  /*Shape(0); */ }    //Not HERE

void get_data()
{   
     cout<<"\nRadius: ";
     cin>>x;
}

void display_area()
{
     cout<<"\nArea: "<<y*x*x;}
};

【讨论】:

    【解决方案2】:

    要调用基本构造函数,您需要使用member initialization list

    变化:

    Circle()
    {
        Shape(0);
    }    //ERROR HERE
    

    Circle() : Shape(0)
    {
    
    }
    

    【讨论】:

    • 感谢 Jose 代码有效,但显示的是整数而不是小数
    • Shape(0) 正在调用第二个构造函数(它接受两个整数,而不是浮点数或双精度数)。由于第一个 int 设置为 0,而 t 设置为 3 * 0 = 0。也许您可能想更改第二个构造函数以接受双精度数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多