我创建了一个程序,它使用虚函数和多态来计算三个不同对象的参数和面积:圆形,矩形和直角三角形。每当我尝试将一个不同的对象类分配给我在测试类中的指针时,它会显示“错误:期望一个类型说明符”:
shape_ptr = new Rectangle;
屏幕截图of error shown
我几乎可以肯定这是一个非常简单的东西,我错过了,但它不是包含头文件,因为我已经在每个班级上完成了这一点而没有任何我能看到的错误。这是我的代码:
基类:
#ifndef SHAPE
#define SHAPE
#include <iostream>
using namespace std;
class Shape {
public:
virtual void compute_area() = 0; // a pure virtual function
virtual void compute_perimeter() = 0; // a pure virtual function
virtual void read_shape_data() = 0; // a pure virtual function
virtual void print_result() { // a virtual function
cout << "The area is " << area << endl;
cout << "The perimeter is " << perim << endl;
}
protected: // protected access specifier
double area, perim;
};
#endif
circle.cpp:
#include "shape.h"
#include <iostream>
using namespace std;
class Circle : public Shape
{
public:
void compute_area() { area = pi * radius; }
void compute_perimeter() { perim = 2 * pi * radius; }
void read_shape_data() {
cout << "Enter radius of the rectangle : ";
cin >> radius;
}
private:
int radius;
double pi = 3.14159265359;
};
rectangle.cpp:
#include "shape.h"
#include <iostream>
using namespace std;
class Rectangle : public Shape
{
public:
void compute_area() { area = width * height; }
void compute_perimeter() { perim = 2 * width + 2 * height; }
void read_shape_data() {
cout << "Enter width of the rectangle : ";
cin >> width;
cout << "Enter height of the rectangle : ";
cin >> height;
}
private:
int width, height;
};
RightTriangle.cpp:
#include "shape.h"
#include <iostream>
using namespace std;
class RightTriangle : public Shape
{
public:
void compute_area() { area = base * height; }
void compute_perimeter() { perim = pow((pow(base, 2) * pow(height, 2)), 2); }
void read_shape_data() {
cout << "Enter base length of triangle : ";
cin >> base;
cout << "Enter height of triangle : ";
cin >> height;
cout <<
}
private:
int radius, base, height;
};
test.cpp(测试类):
#include "shape.h"
#include <iostream>
using namespace std;
int main(){
int choice;
Shape* shape_ptr = NULL;
cout << "Enter 1 for circle, 2 for rectangle, 3 for right angled triangle or 0 for exit";
cin >> choice;
switch (choice){
case 1:
shape_ptr = new Rectangle;
break;
}
shape_ptr->read_shape_data();
shape_ptr->compute_area();
shape_ptr->compute_perimeter();
shape_ptr->print_result();
delete shape_ptr;
return 0;
}
感谢您的时间,我很乐意回答您的任何问题。
答案 0 :(得分:2)
“shape.h”标题不会自动了解sess.run()
等派生类的定义,因此您的测试文件也需要包含这些标题:
Rectangle
看起来您在.cpp文件中定义了派生类。将这些声明移动到头文件中,然后在.cpp文件中定义它们。