我已经关注了代码:
#include <iostream>
using namespace std;
class Weapon
{
protected:
int strength;
char type;
public:
int modified;
int return_strength()
{
return strength;
}
char return_type()
{
return type;
}
void setPower (int val)
{
strength = val;
return;
}
};
class Rock: public Weapon
{
public:
Rock()
{
type='r';
}
bool battle(Weapon w)
{
//Write your solution code below this line
//default return statement below
switch ( w.return_type() ) {
case 'p':
modified = strength / 2;
w.modified = strength * 2;
break;
case 's':
modified = strength * 2;
w.modified = strength / 2;
break;
default:
cout << "Unkown option";
break;
}
if (modified > w.modified )
{
return true;
}
else if (modified < w.modified )
{
return false;
}
else
{
cout << "The strenghs are equal";
return -1;
}
}
};
class Paper: public Weapon
{
public:
Paper()
{
type='p';
}
bool battle(Weapon w)
{
//Write your solution code below this line
//default return statement below
return true;
//remove the default return statement and return your own result
}
};
class Scissors: public Weapon
{
public:
Scissors()
{
type='s';
}
bool battle(Weapon w)
{
//Write your solution code below this line
//default return statement below
return true;
//remove the default return statement and return your own result
}
};
int main()
{
char play1, play2, str_winner;
int str1, str2;
bool winner;
Paper obj_paper;
Rock obj_rock;
Scissors obj_scissors;
Weapon *p1, *p2;
cout << "1st player: Choose Rock (r), Paper (p) or Scissors (s)";
cin >> play1;
cout << "Insert a strength";
cin >> str1;
cout << "2st player: Choose Rock (r), Paper (p) or Scissors (s)";
cin >> play2;
cout << "Insert a strength";
cin >> str2;
switch( play1 ){
case 'r':
p1 = &obj_rock;
case 'p':
p1 = &obj_paper;
case 's':
p1 = &obj_scissors;
}
switch( play2 ){
case 'r':
p2 = &obj_rock;
case 'p':
p2 = &obj_paper;
case 's':
p2 = &obj_scissors;
}
p1->setPower(str1);
p2->setPower(str2);
winner = p1->battle(*p2);
return 0;
}
代码还没有完全完成,但我面临两个问题。
1)当我尝试从其中一个派生类访问战斗时,它表示没有该名称的成员。似乎 p1 只能访问基类。当我让指针指向派生类时,c ++现在允许我访问派生类中的函数吗?
2)有没有更好的方法来确定在运行时我应该使用哪个派生类。如你所见,我从用户那里得到两个输入,告诉他想要什么武器,然后我需要指出要考虑的对象。
谢谢
答案 0 :(得分:0)
你可以做一个安全的dynamic_cast&lt;&gt;到派生类,如果它不为null,则调用派生类方法
我会在基类中添加一个虚方法或纯方法或默认实现,并让每个武器超载它。
答案 1 :(得分:0)
2
switch(play1 ){
case 'r':
p1 = &obj_rock;
...
虽然您正在做的事情很好,但我认为您要做的是p1 = new Rock(){当您使用该记忆时,请执行删除p1}。
这也是一个人们使用factory pattern
的更通用的问题