简体   繁体   English

C++ 继承(覆盖构造函数)

[英]C++ inheritance (overriding constructors)

I am learning OpenGL w/ C++.我正在学习带有 C++ 的 OpenGL。 I am building the asteroids game as an exercise.我正在构建小行星游戏作为练习。 I'm not quite sure how to override the constructors:我不太确定如何覆盖构造函数:

projectile.h弹丸.h

class projectile
{

protected:
    float x;
    float y;

public:

    projectile();
    projectile(float, float);

    float get_x() const;
    float get_y() const;

    void move();
};

projectile.cpp投射物.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;
}

asteroid.h小行星.h

#include "projectile.h"

class asteroid : public projectile
{
    float radius;

public:
    asteroid();
    asteroid(float X, float Y);
    float get_radius();
};

main.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;
}

error I'm getting:我得到的错误:

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

You need a asteroid.cpp .你需要一个asteroid.cpp

Even though inheriting from projectile , for non-default constructors (ie, asteroid(float,float) ), you still need to define the child class constructor.即使继承自projectile ,对于非默认构造函数(即asteroid(float,float) ),您仍然需要定义子类构造函数。

You'll also need to define get_radius , as it's not defined in your base class.您还需要定义get_radius ,因为它没有在您的基类中定义。

Here's how that might look (I've taken the liberty of passing values for radius into both ctors):这是它的外观(我冒昧地将半径值传递给两个 ctors):

#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;
}

您可以使用:语法来调用父级的构造函数:

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

Ok, just figured it out.好吧,刚刚想通了。

I actually don't have asteroid constructors defined because I thought they would inherit.我实际上没有定义小行星构造函数,因为我认为它们会继承。 But I think I have to do the following in asteroid.h:但我认为我必须在 asteroid.h 中执行以下操作:

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

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

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