简体   繁体   English

C ++中的类和方法继承

[英]Class & method inheritance in c++

So, I thought I get it, but I don't... This is my header file shapes.h : 所以,我以为我明白了,但是我没有...这是我的头文件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: 然后在shapes.cpp其实现为:

#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: 在我的main.cpp我做了:

#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 您声明了Shape::areaShape::rotate但未定义它们

One solution would be to change shapes.h like this: 一种解决方案是更改shape.h,如下所示:

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: 另一种解决方案是改为将定义添加到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): 正如juanchopanza所指出的,另一种解决方案是使方法成为纯虚拟方法(这可能是最好的):

class Shape {
public:
    double h;
    double w;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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