Dragon* Dragon::spawn() {
int x = rand() % 5;
int y;
if (!if_locked(x)) //is a function to see if that id is unlocked because i want some dragon to be generated only if you have certain xp so it will call func again until unlocked id is generated
spawn();
else
y = unlocking(m); // Y is generated form 1-5, I have assigned Id to each derive class whosoever id matches Y that pointer will be returned
if (y == 1) {
GroundDragon* pt;
return pt;
}
if (y == 2) {
WaterDragon* st;
return st;
}
if (y == 3) {
IceDragon*bt;
return bt;
}
if (y == 4) {
FireDragon* ct;
return ct;
}
if (y == 5) {
DarkDragon* dark;
return dark;
}
}
如您所见,我在语法上犯了错误,我希望有人可以指导我
函数的返回类型为基类,if语句中的所有类均为派生类
所以我以后可以使用这个功能
template<class T>
void spawner(T*) {// I will spawn() fucntion as perimeter at time of call
T = new T;
}
请原谅我是否在我上次发布该问题时没有引起我的期待,所以我对代码进行了一些修改,希望现在已经很清楚了。
int Dragon::unlocking(Mage m) {
if (m.getxp() <= 50 and m.getxp() <= 100) {
unlock[0] = 1;
cout << "Congratulation GroundDragon unlocked " << endl;
return 1;
}
if (m.getxp() > 100 and m.getxp() < 150) {
unlock[1] = 1;
cout << "Congratulation WaterDragon unlocked " << endl;
return 2;
}
if (m.getxp() > 150 and m.getxp() < 175) {
unlock[2] = 1;
cout << "Congratulation IceDragon unlocked " << endl;
return 3;
}
if (m.getxp() > 175 and m.getxp() < 500) {
unlock[3] = 1;
cout << "Congratulation FireDragon unlocked " << endl;
return 4;
}
if (m.getxp() > 500) {
unlock[4] = 1;
cout << "Congratulation DarkDragon unlocked " << endl;
return 5;
}
}
bool Dragon::if_locked(int x) {
if (unlock[x] == 1) {
return true;
}
else
return false;
}
*我对smartpointer不满意(我以前从未使用过它们,但是如果您向我展示如何将其称为主要对象,我希望使用它们*
我使用了原始指针,但仍然显示错误,请帮助mw
最佳答案
这个想法很合理,只是执行失败。
如果您希望有一个工厂函数将返回不同的对象,然后这些对象将进行多态操作,那么这非常好,其中一件重要的事情是-您需要返回实际的对象。
您的工厂函数的返回类型为Dragon*
。这意味着无论您返回什么值,它都将是一个指向Dragon
(某种程度上)的指针。但是,该指针的值可以指向实际上是FireDragon
,IceDragon
等实例的对象。创建此类对象的实例时,指向该实例的指针可以转换为适当的返回类型并返回。
在您的情况下,虽然您正在创建类型为dragon-to-some-sort-dragon的临时对象,但实际上并没有用实例填充它们。它们都是用未指定的值创建的,然后将该值转换为Dragon*
类型的未指定值,而无法提取其转换类型的信息。
因此,为了使其能够以通常的方式工作,我们只需要创建一个适当类型的新实例并将其返回即可。转让所有权时,我们永远都不想从函数返回原始指针,因此std::unique_ptr
是更好的选择:
std::unique_ptr<Dragon> Dragon::spawn() {
int x = rand() % 5;
/* note - this bit of code doesn't make any sense whatsoever
int y;
if (!if_locked(x)) //is a different function
spawn();
else
y = unlocking(m); //is also a different function
*/
// note that `rand() % 5` will produce values 0 through 4.
switch(x) {
case 0: return std::make_unique<GroundDragon>();
case 1: return std::make_unique<WaterDragon>();
case 2: return std::make_unique<IceDragon>();
case 3: return std::make_unique<FireDragon>();
case 4: return std::make_unique<DarkDragon>();
}
}
现在您根本不需要
spawner
函数;您可以直接使用返回值。
关于c++ - 我想要返回类型的指针,但我想让我的函数返回派生类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875507/