[英]Class & method inheritance in c++
所以,我以為我明白了,但是我沒有...這是我的頭文件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
然后在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;
}
在我的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();
}
...
我得到這個錯誤:
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.
我以為該錯誤說明了一切,並尋找了類似的問題,我找到了很多答案,但無法在我的代碼中找出錯誤...
您聲明了Shape::area
和Shape::rotate
但未定義它們
一種解決方案是更改shape.h,如下所示:
class Shape {
public:
double h;
double w;
virtual double area(void) { return 0; }
virtual void rotate(void) {}
};
另一種解決方案是改為將定義添加到shapes.cpp:
double Shape::area() { return 0; }
void Shape::rotate() {}
正如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.