简体   繁体   中英

Class & method inheritance in c++

So, I thought I get it, but I don't... This is my header file shapes.h :

#ifndef __shapes__
#define __shapes__

class Shape {

public:
    double h;
    double w;

    virtual double area(void);

    virtual void rotate(void);
};

class Rectangle : public Shape {
public:
    Rectangle(double h, double w);

    double area(void);

    void rotate(void);

private:
    double h;
    double w;
};

#endif

and then I implement it in shapes.cpp as:

#include "shapes.h"
#include <cmath>
#include <math.h>

/*
 * Rectangle methods
 */
Rectangle::Rectangle(double height, double width) {
    this->h = height;
    this->w = width;
}

double Rectangle::area() {
    return this->h * this->w;
}

void Rectangle::rotate() {
    double temp = this->h;

    this->h = this->w;
    this->w = temp;
}

And in my main.cpp I do:

#include <vector>
#include "shapes.h"

using namespace std;

int main(void){

    vector<Shape *> shapes;

    Rectangle u(2,5);
    shapes.push_back(&u);
    Rectangle v(3, 4);
    shapes.push_back(&v);

    double area = 0;
    for(Shape * p : shapes){
        area += p->area();
    }
    ...

And I get this error:

Undefined symbols for architecture x86_64:
    "typeinfo for Shape", referenced from:
      typeinfo for Rectangle in shapes-12a86a.o
  "vtable for Shape", referenced from:
      Shape::Shape() in shapes-12a86a.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.

I assumed that the error speaks for itself and looked up for similar questions, to which I found a lot answers, but could not figure out the mistake in my code...

You declared Shape::area and Shape::rotate but you did not define them

One solution would be to change shapes.h like this:

class Shape {
public:
    double h;
    double w;

    virtual double area(void) { return 0; }
    virtual void rotate(void) {}
};

Another solution is to instead add the definitions to shapes.cpp:

double Shape::area() { return 0; }
void Shape::rotate() {}

As juanchopanza pointed out, another solution is to make the methods pure virtual (which is probably best):

class Shape {
public:
    double h;
    double w;

    virtual double area(void) = 0;
    virtual void rotate(void) = 0;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM