为什么不允许继承成员? [英] Why is inherited member not allowed?
问题描述
我是C ++的初学者,我正在做一个关于抽象类和继承的练习。
I'm beginner to C++ and I'm doing one of the exercises about abstract class and inheritance.
这是我的抽象类:
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
virtual void area();
virtual void perimeter();
virtual void volume();
};
#endif
这是我实现抽象类的具体类:
This is my concrete class that implements the abstract class:
#include <iostream>
#include <cmath>
#include "Shape.h"
using namespace std;
class Circle : public Shape
{
public:
Circle(int);
private:
int r;
};
Circle::Circle(int rad)
{
r = rad;
}
void Circle::area()
{
cout << "Area of this cirle = " << 3.14 * pow(r, 2) << endl;
}
void Circle::perimeter()
{
cout << "Perimeter of this cirle = " << 2 * 3.14 * r << endl;
}
void Circle::volume()
{
cout << "Volume is not defined for circle." << endl;
}
code>,,
,( / code>类,它显示
错误:不允许继承成员
。我经历了我的类ppt和谷歌的答案,但没有运气。
I got red lines under area()
, perimeter()
, and volume()
in my Circle
class, which showed "Error: inherited member is not allowed"
. I went through my class ppt and googled for answer but no luck. Any help is appreciated.
推荐答案
您必须将重写的函数声明为类定义的一部分
You have to declare the over-ridden functions as part of your class definition
class Circle : public Shape
{
public:
Circle(int);
virtual void area(); // overrides Shape::area
void perimeter(); // overrides Shape::perimeter
virtual void volume();
private:
int r;
};
请注意,使用 virtual
可选。
如nm注意,你还应该在 Shape
中包含一个虚拟析构函数。您可能还希望使其虚拟函数纯虚拟(基于您对 Shape
的抽象的注释)
As n.m. noted, you should also include a virtual destructor in Shape
. You may also want to make its virtual functions pure virtual (based on your comment about Shape
being abstract)
class Shape
{
public:
virtual ~Shape() {}
virtual void area() = 0;
virtual void perimeter() = 0;
virtual void volume() = 0;
};
这篇关于为什么不允许继承成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!