【发布时间】:2015-04-04 21:43:16
【问题描述】:
我使用基类实现了继承设计
// Msg.hpp
#ifndef __MSG_H_
#define __MSG_H_
#include <iostream>
#include <string>
class Msg {
public:
virtual void buildMsg(std::string &msg) = 0;
};
#endif
在我的示例中,两个派生类:
// GoodMorningMsg.hpp
#ifndef __GOOD_MORNING_MSG_H_
#define __GOOD_MORNING_MSG_H_
#include "Msg.hpp"
class GoodMorningMsg : public Msg {
public:
void buildMsg(std::string &msg) {
msg.append("Good Morning");
};
};
#endif
// GoodEveningMsg.hpp
#ifndef __GOOD_EVENING_MSG_H_
#define __GOOD_EVENING_MSG_H_
#include "Msg.hpp"
class GoodEveningMsg : public Msg {
public:
void buildMsg(std::string &msg) {
msg.append("Good Evning");
};
};
#endif
为了避免 switch 的需要,我通常会将 GoodMorningMsg 和 GoodEveningMsg 类的实例放在 std::map 对象中并且每次执行相关对象来构建我的消息。
由于我正在为嵌入式系统编写代码,因此我不允许使用动态分配(换句话说,STL 库)。
假设我事先知道我需要创建的实例的大小,我该如何实现通用代码并避免在我的代码中使用开关?
更新 我解决了一个问题,但第二部分仍然开放。 这是我的 main.cpp:
#include <iostream>
#include <map>
#include "Const.hpp"
#include "Msg.hpp"
#include "GoodMorningMsg.hpp"
#include "GoodEveningMsg.hpp"
void printMsg( std::map<std::string, Msg*> msgMapObject , std::string msg , const std::string & strToFind ) {
std::map<std::string, Msg*>::iterator it = msgMapObject.find( strToFind );
if(it != msgMapObject.end()) {
it->second->buildMsg( msg );
std::cout << "Message: " << msg << std::endl;
}
}
int main() {
GoodMorningMsg goodMorningMsg = GoodMorningMsg();
GoodEveningMsg goodEveningMsg = GoodEveningMsg();
std::map<std::string, Msg*> msgMap;
msgMap.insert(std::make_pair( std::string("GoodMorning") , &goodMorningMsg ) );
msgMap.insert(std::make_pair( std::string("GoodEvening") , &goodEveningMsg ) ) ;
std::string msg("I wish you ");
printMsg( msgMap , msg , std::string("GoodMorning") );
printMsg( msgMap , msg , std::string("GoodEvening") );
return 0;
}
而不是每次都创建 GoodMorningMsg 或 GoodEveningMsg 类的实例,我想放置那些等同于 std::map 的东西,但它不能抛出异常,因为我正在为嵌入式系统应用程序编程。
【问题讨论】:
-
如果你必须在运行时决定,我看不出有任何方法可以避免虚拟调用/动态分配,但我可能是错的(因为我学会了在 C++ 中永远不要说:) ) 如果您在编译时决定,那么您可以使用多种技术,可能使用标签是最好的。