[英]How to access Constructor of Parent class in C++ with parent class having a pure virtual function
I am trying to create Circle and Rectangle from Class Shape.我正在尝试从类形状创建圆形和矩形。 I want y to be assigned pi if I call Shape() constructor with a parameter (from circle class).
如果我使用参数(来自圆类)调用 Shape() 构造函数,我希望 y 被分配 pi 。 Since Shape has a purely virtual function the compiler is showing error.
由于 Shape 具有纯虚函数,因此编译器显示错误。 How can I overcome this error.
我怎样才能克服这个错误。 And why is default parameter running correctly then?
为什么默认参数运行正确呢? Also I tried this->Shape(0) from Circle class.
我也从 Circle 类中尝试了 this->Shape(0) 。 Compiler is saying "Invalid use of this"
编译器说“Invalid use of this”
#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;}
};
To call the base constructor you need to use the member initialization list
.要调用基本构造函数,您需要使用
member initialization list
。
Change:改变:
Circle()
{
Shape(0);
} //ERROR HERE
To到
Circle() : Shape(0)
{
}
base classes are always initialized before the constructor's block runs, so you do it in the constructor's member initialization list ..基类总是在构造函数块运行之前初始化,所以你在构造函数的成员初始化列表中进行初始化..
I also fixed another bug in your code.... You are doing some narrowing conversions, which wouldn't work as you want...我还修复了您代码中的另一个错误....您正在进行一些缩小转换,这不会如您所愿...
#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;}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.