【发布时间】:2016-10-03 21:20:09
【问题描述】:
我有以下代码:
#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) 有没有更好的方法来确定我应该在运行时使用哪个派生类。如您所见,我从用户那里得到两个输入,告诉他他想要什么武器,然后我需要指出要考虑的对象。
谢谢
【问题讨论】:
标签: c++ inheritance polymorphism