gpt4 book ai didi

c++ - C++中的类和方法继承

转载 作者:行者123 更新时间:2023-11-28 04:56:40 25 4
gpt4 key购买 nike

所以,我以为我明白了,但我没有...这是我的头文件 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::areaShape::rotate 但你没有定义它们

一种解决方案是像这样更改 shapes.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;
};

关于c++ - C++中的类和方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46986855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com