c ++指针转换过载

问题描述 投票:-1回答:1

基本问题是有人知道c ++中的方法吗? Class 2是Class1的子类,它必须保持这种方式。

Class1* a;
Class2* b = (Class2*)a;

basically allowing you
Class1* a;
Class2* b = a;


// tried this but didn't seem to work
class Class1
{
    operator Class2*() { return (Class2*)this; }
}

如果这是一个迟钝的问题/重复,我真的找不到任何对不起,但我没有完全理解这一点。如果someoen有类似的东西,将不胜感激。

编辑:一些额外的信息Class1 = baseclass例如Player Class2 =子类,例如Weapon

Class1包含一个指向Subclass的指针,该子类具有与origin相同的值

玩家有一个指向武器的指针基本上我想要做的是

GetEntity返回一个类型为Player的指针(但返回值也可能是武器)

基本上现在我想要做的就是自动化铸造它的过程

Player* p = GetEntity(0);
Player* p2 = GetEntity(1);
Weapon wpn = (Weapon*)p2;

//so that you are able to do
Weapon wpn = p2;

// Also that Stuff like that would be possible
void Test(Weapon *wpn);

Player *player = GetEntity(1);
// Yes I know this works Test((Weapon*)player) but I am lazy and that's the goal
Test(player);

没有铸造它。

c++ casting overloading operator-keyword
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.