抽象方法具有它没有体的属性.因此,当具体类扩展抽象类时,它必须实现该抽象方法.
所以我的问题是如何覆盖抽象方法?
是否有可能编写一个通用基类,所有其他类(除了它)公开并实际上继承?(gcc有解决方法吗?).最好不要明确地继承...因为我希望标准库的东西也从这里继承....这是明智的做法吗?
如果你投票,请解释原因(我相信这是一个合法的问题,即使它是一个愚蠢的事情,它可能是,但这是问题的一部分)
班级Enemy,Ore是班级的孩子Entity.上课Asteroid是孩子的Enemy.当我的船接触任何实体时,会触发以下代码.
几句话的代码是:当船舶接触矿石时,将矿石添加到船舶的库存中并从筛网中移除该矿石.当船接触敌人时,检查它是什么敌人.如果它是小行星,请向后推船,降低它的健康状况并删除该小行星.
if (entities[j] is Ore)
{ pilots[i].Ship.InventoryAdd(entities[j]); entities.RemoveAt(j--); }
if (entities[j] is Enemy)
{
if(entities[j] is Asteroid)
{
pilots[i].Ship.AddForce(entities[j].Force * (entities[j] as Enemy).Damage);
pilots[i].Ship.HP -= (entities[j] as Enemy).Damage;
entities.RemoveAt(j);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我看到在一次更新或框架中可以触发的问题,两次碰撞都在发生(船舶与小行星和船舶与矿石),我将解决这个问题.此外,这是整个代码,而不仅仅是所有情况的一部分.现在,我只在屏幕上有矿石和小行星(和一艘船).
船舶与矿石碰撞中出现了问题.我的船被推回去了.但我只在船上与小行星上做到这一点.这意味着该计划将矿石视为小行星,而不是.我多次检查了所有这些东西.是的,他们都有相同的父母,但如果我问一个实例是否是小行星,他怎么能说"是的,而且它也是一个矿石",当它不是时.
如果我要求一个Asteroid实例,如果它是Entity and Enemy和Asteroid类,我会得到答案,我总是得到一个答案"是",但是Ore怎么能成为小行星呢?
问题是:这背后的逻辑是什么,如何以正确的方式检查?还要注意,增加力量的线将为所有敌人射击,而不仅仅是小行星,这是现在的情况.
我总是读到C++中的C风格演员与reinterpret_cast相同.但是,我刚刚在Visual Studio中测试了这段代码,看起来C样式的转换与静态转换的行为相同.有人知道为什么吗?这似乎是一个错误......
#include <string>
#include <iostream>
class Thing1
{
std::string theString;
public:
Thing1(const std::string& theString) : theString(theString)
{
//
}
std::string getTheString()
{
return theString;
}
};
class Thing2
{
std::string theString;
public:
Thing2(const std::string& theString) : theString(theString)
{
//
}
std::string getTheString()
{
return theString;
}
};
class Thing3 : public Thing1, public Thing2
{
public:
Thing3(const std::string& theString1, const std::string& theString2) : Thing1(theString1), Thing2(theString2)
{
//
}
};
int main()
{
Thing3* thing3 = new Thing3("string1", "string2");
uintptr_t …Run Code Online (Sandbox Code Playgroud) 假设我有这段代码:
class Vehicle {
virtual const char* media() const = 0;
virtual unsigned speed() const = 0;
} V, *PV;
class LandVehicle : public Vehicle {
const char* media() const override{ return "Land";}
} L, *PL;
class Train : public LandVehicle{
virtual unsigned speed() const override {return 130;}
} T, *PT;
Run Code Online (Sandbox Code Playgroud)
我有几个问题:D
1)LandVehicle没有实现速度().这是一个错误,如果是这样,会出现什么样的错误?或者它只是使它成为一个抽象类?
2)是正确使用方法media()中的类LandVehicle中的关键字覆盖?作为抽象类的派生类,它真的覆盖了方法吗?
3)与Train的speed()方法中的覆盖相同.
4)现在培养一个具体课程?
5)是否有必要在LandVehicle的media()方法的声明中添加关键字virtual?
6)如果我在Train类中添加此方法:
const char* media() const{ return "Just a train";}
Run Code Online (Sandbox Code Playgroud)
它隐藏了LandVehicle的媒体()还是覆盖它?
7)在6中添加方法后,可以在Train类中访问LandVehicle的media()吗?