c++
1#include <iostream> 2#include <string> 3#include "Shape.h" 4#include "Circle.h" 5#include "Rect.h" 6 7int main(){ 8 Shape** shapes = new Shape*[3]; 9 Circle c1(0,0,2); //純粋仮想関数を含むオブジェクトは生成できない 10 Circle c2(1,1,5); 11 Rect r1(5,5,8,4); 12 shapes[0] = &c1; 13 shapes[1] = &c2; 14 shapes[2] = &r1; 15 for(int i=0; i<3; i++){ 16 std::cout << shapes[i]->area() << std::endl; 17 } 18 delete[] shapes; 19}
上のソースコードを実行したところ、
error: cannot declare variable 'c1' to be of abstract type 'Circle'
error: cannot declare variable 'c2' to be of abstract type 'Circle'
error: cannot declare variable 'r1' to be of abstract type 'Rect'
のようなエラーがでました。
調べると、「純粋仮想関数」を持つクラスのオブジェクトは作れないようで、
virtualがついているメソッドを探したのですが見つかりませんでした。
原因が分からないので教えていただきたいです。
(ちなみに、Rect.h, Circle.hにもエラーが出ています。)
また、Shape.h, Circle.h, Rect.hは次のようになります。
c++
1#ifndef SHAPE_H_ 2#define SHAPE_H_ 3 4#include <sstream> 5#include <string> 6 7class Shape{ 8public: 9 virtual ~Shape() = 0; 10 virtual int area() const = 0; 11 //virtual std::String toString() const = 0; 12}; 13 14inline Shape::~Shape() {}; 15 16/* 17inline std::ostream& operator<<(std::ostream& s, const Shape& shape){ 18 return s << shape.toString(); 19} 20*/ 21 22#endif /* SHAPE_H_ */
c++
1#ifndef CIRCLE_H_ 2#define CIRCLE_H_ 3 4#include "Shape.h" 5#include <math.h> 6 7class Circle: public Shape{ 8protected: //継承先で参照するため 9 int x, y, r; 10public: 11 Circle(int xx, int yy, int rr){ 12 x(xx), y(yy), r(rr) {} 13 } 14 ~Circle() {} 15 int area() { return r * r * M_PI; } 16}; 17 18#endif /* CIRCLE_H_ */
c++
1#ifndef RECT_H_ 2#define RECT_H_ 3 4#include "Shape.h" 5 6class Rect: public Shape{ 7protected: //継承先で参照するため 8 int x, y, w, h; 9public: 10 Rect(int xx, int yy, int ww, int hh){ 11 x(xx), y(yy), w(ww), h(hh) {} 12 } 13 ~Rect() {} 14 int area() { return w * h; } 15}; 16 17#endif /* RECT_H_ */

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。