【发布时间】:2013-02-27 16:46:56
【问题描述】:
我是 C++ 的初学者,我正在做一个关于抽象类和继承的练习。
这是我的抽象类:
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
virtual void area();
virtual void perimeter();
virtual void volume();
};
#endif
这是我实现抽象类的具体类:
#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;
}
在我的Circle 课程中,area()、perimeter() 和volume() 下出现红线,显示为"Error: inherited member is not allowed"。我浏览了我的课堂 ppt 并搜索了答案,但没有运气。任何帮助表示赞赏。
【问题讨论】:
-
你仍然需要在派生类中声明虚方法。
-
Shape看起来并不抽象。它的成员函数应该是纯虚函数。此外,它应该声明一个虚拟析构函数。 -
别忘了声明
virtual ~Shape() {} -
只是想更正有问题的术语。抽象的意思是头文件,具体的意思是定义文件。不确定您真正寻找的是纯虚拟方法。
标签: c++ inheritance