首先,让我用“我是 C++ 新手”作为这个问题的序言!这可能会变得非常简单,我会觉得很愚蠢,但现在我真的可以使用帮助。我知道如何使用抽象类来做到这一点,但我不能在这里使用抽象类。此外,如果有更好的方法来执行此操作,我愿意接受建议。
我有一个 ClientCommand(基类)和一个 MasterCommand(扩展基类)
MasterCommand 可以做 ClientCommand 可以做的所有事情,还有一些方法。
在我的应用程序中,我想为两个命令使用相同的名称。如果该对象是一个客户端,那么它将仅限于客户端方法。如果对象是 Master,那么它将具有所有客户端方法以及 Master 方法。
我知道一定有办法做到这一点。
- 我没有正确转换
- 我没有正确构建它
- 或者我做错了什么
这是我的测试代码:
基础类标题:
#ifndef __OPCommand_H_
#define __OPCommand_H_
class OPCommand {
public:
virtual void doSomething();
void doClientStuff();
};
#endif //__OPCommand_H_
基类主体:
#include "OPCommand.h"
void OPCommand::doSomething() {
// TODO - implement OPClientCommand::doSomething
throw "Not yet implemented";
}
void OPCommand::doClientStuff() {
// TODO - implement OPClientCommand::doClientStuff
throw "Not yet implemented";
}
扩展类标题:
#ifndef __OPMasterCommand_H_
#define __OPMasterCommand_H_
#include "OPCommand.h"
class OPMasterCommand : public OPCommand {
public:
void doSomething();
void doMasterStuff();
};
#endif //__OPMasterCommand_H_
扩展类主体:
#include "OPMasterCommand.h"
void OPMasterCommand::doSomething() {
// TODO - implement OPMasterCommand::doSomething
throw "Not yet implemented";
}
void OPMasterCommand::doMasterStuff() {
// TODO - implement OPMasterCommand::doMasterStuff
throw "Not yet implemented";
}
测试类标题:
#ifndef __TestMe_H_
#define __TestMe_H_
#include "OPMasterCommand.h"
#include "OPCommand.h"
class TestMe {
public:
OPCommand* command;
OPMasterCommand* masterCommand;
public:
void startHere();
OPMasterCommand* getMasterCommand();
OPCommand* getCommand();
bool isMaster();
};
#endif //__TestMe_H_
测试类主体:
密切注意 startHere 方法:
#include "TestMe.h"
void TestMe::startHere() {
if (isMaster()) {
masterCommand = getMasterCommand();
} else {
command = getCommand();
}
// Here - How can I point to or cast to the appropriate type, so I can use the same name everywhere in my code?
}
OPMasterCommand* TestMe::getMasterCommand() {
if (!masterCommand) {
masterCommand = new OPMasterCommand();
}
//command = dynamic_cast<OPCommand*> (masterCommand);
return masterCommand;
}
OPCommand* TestMe::getCommand() {
if (!command) {
command = new OPCommand();
}
return command;
}
bool TestMe::isMaster() {
return true;
}
我无法构建它。现在我正在重新定义“OPCommand”
最佳答案
我的心理调试技巧告诉我,由于您是 C++ 的新手,您忘记了 header 包含保护(这是您看到的 redefinition of 'OPCommand'
错误的一个非常常见的原因)。
尝试在您的头文件中加入类似这样的内容(更改每个头文件的名称):
#ifndef OPCOMMAND_H_included
#define OPCOMMAND_H_included
<original header contents>
#endif
关于C++如何扩展一个类并转换为具有相同名称的适当类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28946611/