C++继承(重写构造函数)
C++ inheritance (overriding constructors)
我正在学习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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 重写子类构造函数中的父类变量
- 正在接口构造函数中调用重写的接口方法
- C++继承-从构造函数调用重写
- 如何用参数重写构造函数并在单独的文件中实现它
- C++应该重写派生类中的复制构造函数吗
- 在构造函数中使用重写方法的替代方法,Java
- C++继承(重写构造函数)
- C++ 继承构造函数重写
- 为什么构造函数忽略重写的虚函数
- 重写默认构造函数/析构函数而不实现它们
- 令人困惑的继承示例.构造函数被重写,但函数不是.为什么
- 如何重写基类中的构造函数
- 重写CObList MFC的复制构造函数
- 具有指针成员且没有重写复制构造函数的类
- C++:在基类的构造函数中调用重写的方法
- 如何从父类构造函数引用重写的静态方法