C++继承(重写构造函数)

C++ inheritance (overriding constructors)

本文关键字:构造函数 重写 继承 C++      更新时间:2023-10-16

我正在学习OpenGL w/C++。 我正在构建小行星游戏作为练习。 我不太确定如何覆盖构造函数:

弹丸.h

class projectile
{
protected:
    float x;
    float y;
public:
    projectile();
    projectile(float, float);
    float get_x() const;
    float get_y() const;
    void move();
};

弹丸.cpp

projectile::projectile()
{
    x = 0.0f;
    y = 0.0f;
}
projectile::projectile(float X, float Y)
{
    x = X;
    y = Y;
}
float projectile::get_x() const
{
    return x;
}
float projectile::get_y() const
{
    return y;
}
void projectile::move()
{
    x += 0.5f;
    y += 0.5f;
}

小行星H

#include "projectile.h"
class asteroid : public projectile
{
    float radius;
public:
    asteroid();
    asteroid(float X, float Y);
    float get_radius();
};

主.cpp

#include <iostream>
#include "asteroid.h"
using namespace std;
int main()
{
    asteroid a(1.0f, 2.0f);
    cout << a.get_x() << endl;
    cout << a.get_y() << endl;
}

我得到的错误:

main.cpp:(.text+0x20): undefined reference to `asteroid::asteroid(float, float)'
可以使用

:语法调用父级的构造函数:

asteroid(float X, float Y) : projectile (x ,y);

好的,刚刚想通了。

我实际上没有定义小行星构造函数,因为我认为它们会继承。但我想我必须在asteroid.h中执行以下操作:

asteroid(float X, float Y) : projectile(X, Y){];

你需要一个asteroid.cpp

即使继承自projectile,对于非默认构造函数(即asteroid(float,float)),您仍然需要定义子类构造函数。

您还需要定义 get_radius ,因为它未在基类中定义。

这是它的外观(我已经冒昧地将半径的值传递到两个 ctor 中):

#include "asteroid.h"
asteroid::asteroid(float r)
    : projectile()
{
    radius = r;
}
asteroid::asteroid(float x, float y, float r)
    : projectile(x, y)
{
    radius = r;
}
float asteroid::get_radius()
{
    return radius;
}