//QuizShape.h
#ifndef QUIZSHAPE_H
#define QUIZHAPE_H
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class QuizShape
{
protected:
//outer and inner symbols, and label
char border, inner;
string quizLabel;
public:
//base class constructor with defaults
QuizShape(char out = '*', char in = '+', string name = "3x3 Square")
{
border = out;
inner = in;
quizLabel = name;
cout << "base class constructor, values set" << endl << endl;
};
//getters
char getBorder() const
{ return border; }
char getInner() const
{ return inner; }
string getQuizLabel() const
{ return quizLabel; }
//virtual functions to be defined later
virtual void draw( ) = 0;
virtual int getArea( ) = 0;
virtual int getPerimeter( ) = 0;
};
class Rectangle : public QuizShape
{
protected:
//height and with of a rectangle to be drawn
int height, width;
public:
//derived class constructor
Rectangle(char out, char in, string name,
int h = 3, int w = 3):QuizShape(out, in, name)
{
height = h;
width = w;
cout << "derived class constructor, values set" << endl << endl;
}
//getters
int getHeight() const
{ return height; }
int getWidth() const
{ return width; }
//*********************************************
virtual void draw(const Rectangle &rect1)
{
cout << "draw func" << endl;
cout << rect1.height << endl;
cout << rect1.getWidth() << endl;
cout << rect1.getQuizLabel() << endl;
}
virtual int getArea(const Rectangle &rect2)
{
cout << "area func" << endl;
cout << rect2.getInner() << endl;
cout << rect2.getBorder() << endl;
}
virtual int getPerimeter(const Rectangle &rect3)
{
cout << "perim func" << endl;
cout << rect3.height << endl;
cout << rect3.getWidth() << endl;
cout << rect3.getQuizLabel() << endl;
}
//************************************************
};
#endif
到目前为止,这些是类类型。
//QuizShape.cpp
#include "QuizShape.h"
这目前只能桥接文件。
//pass7.cpp
#include "QuizShape.cpp"
int main()
{
Rectangle r1('+', '-', "lol", 4, 5);
cout << r1.getHeight() << endl;
cout << r1.getWidth() << endl;
cout << r1.getInner() << endl;
cout << r1.getBorder() << endl;
cout << r1.getQuizLabel() << endl;
system("pause");
return 0;
}
代码将无法编译,因为Rectangle应该是一个抽象类,当将鼠标悬停在r1
中的main
声明时,我收到错误
“抽象类类型的对象”不允许使用“矩形”。
我已经在本网站和其他网站上检查了其他答案,但没有找到解决问题的方法。
注意:我理解虚函数的语句以= 0结尾;使班级成为一个抽象的班级。 QuizShape应该是抽象的。我已经在Rectangle中定义了虚函数,但它仍然是一个抽象类。
如何修改虚函数Rectangle类以使Rectangle不再是抽象的?
答案 0 :(得分:2)
抽象类QuizShape
中的方法是:
virtual void draw( ) = 0;
virtual int getArea( ) = 0;
virtual int getPerimeter( ) = 0;
但在Rectangle
中,他们将const Rectangle &rect1
作为参数,因此您可以隐藏方法而不会覆盖抽象方法。您需要在Rectangle
中使用与抽象基类中的方法具有相同签名的方法。
答案 1 :(得分:0)
重写的方法必须具有完全相同的签名,在派生类中为它们赋予参数。