coz*_*zos 2 c++ oop abstract-class copy-constructor
如何将派生类复制到另一个?
我在术语上有缺陷,所以我将尝试用一个例子来说明.
我们正在玩电脑玩家和人类玩家的纸牌游戏.卡和命令是其他类.
class Player
{
Card *Hand[4];
// etc...
};
class Human: public Player
{
Command getCommand();
void PlayCard(Card card);
void quit();
// etc...
};
class Computer: public Player
{
Command ai();
void PlayCard(Card card);
// etc...
};
Run Code Online (Sandbox Code Playgroud)
在我们的主要功能的某个地方......
// ...
Human p1; // Assume initialized and usable.
if(p1.getCommand() == QUIT)
{
cout << "PLAYER 1 RAGEQUITS WHAT A NOOB LOL << endl;
cout << "A COMPUTER WILL NOW TAKE OVER." << endl;
p1.quit()
p1 = new Computer(); // THE IDEA BEING THAT WE WANT TO PRESERVE p1's MEMBERS.
}
// ...
Run Code Online (Sandbox Code Playgroud)
我想要做的是将p1转换为"计算机",同时保留其成员的状态.
我们是否使用复制构造函数来执行此操作?如果没有,你使用什么方法?
编辑:这是使用赋值运算符的方式吗?
Computer& Human::operator=(const Human &h) // Assignment operator
{
Hand = h.Hand;
member2 = h.member2;
member3 = h.member3;
...
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我们需要删除/释放主要内容吗?
你有一个设计问题.如果你想在保持公共成员变量的同时将玩家从人类切换到计算机,那么你应该以这种方式构建你的类.
class Player
{
public:
friend class Human; // These friends are necessary if the controllers
friend class Computer; // need access to Player's private data.
Card hand[4];
Controller* controller;
};
class Controller
{
public:
virtual Command getCommand(Player const&) = 0;
};
class Human : public Controller
{
public:
Command getCommand(Player const&) { /* get command from user input */ }
};
class Computer : public Controller
{
public:
Command getCommand(Player const&) { /* get command from AI */ }
};
Run Code Online (Sandbox Code Playgroud)
然后,当您需要从人体切换到计算机时,只需更换控制器即可.
p1->controller = new Computer();
Run Code Online (Sandbox Code Playgroud)
这样,卡片将被维护,只有控制机制才会被改变.
| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |