【发布时间】:2010-12-13 11:51:08
【问题描述】:
我需要从一个基类创建多个类(超过 50 个),唯一的区别在于派生类的名称。
例如,我的基类定义为:
class BaseError : public std::exception
{
private:
int osErrorCode;
const std::string errorMsg;
public:
int ec;
BaseError () : std::exception(), errorMsg() {}
BaseError (int errorCode, int osErrCode, const std::string& msg)
: std::exception(), errorMsg(msg)
{
ec = errorCode;
osErrorCode = osErrCode;
}
BaseError (const BaseError& other)
: std::exception(other), errorMsg(other.errorMsg)
{
ec = other.errorCode;
osErrorCode = other.osErrorCode;
}
const std::string& errorMessage() const { return errorMsg; }
virtual ~BaseError() throw(){}
}
我必须从这个基类创建很多派生类,每个派生类都有自己的构造函数、复制构造函数和虚拟析构函数,目前我正在复制/粘贴代码,在必要时更改名称:
class FileError : public BaseError{
private:
const std::string error_msg;
public:
FileError () :BaseError(), error_msg() {}
FileError (int errorCode, int osErrorCode, const std::string& errorMessage)
:BaseError(errorCode, osErrorCode, errorMessage){}
virtual ~FileError() throw(){}
};
问题: 有没有办法让这些类使用模板创建,这样就不会重复实现?
【问题讨论】:
-
稍微不相关的评论:与其提供自己的
const std::string& errorMessage() constgetter,不如重新实现通过继承std::exception获得的虚拟const char *std::exception::what() const函数。 -
为什么需要派生类?一个简单的
typedef还不够吗?据我所知,派生类没有任何用处。 -
如果你的派生类的行为保持不变,那么为什么不去模板化类呢?
-
另一个远程相关的评论:如果您的所有异常(可以)都有消息,请考虑在您的基类中只拥有一个
std::string errorMsg;成员,而不是在基类中拥有一个成员,然后每个派生类中拥有一个成员.这更有效(就内存和运行时速度而言)。您可以通过提供(受保护的)setter 或将参数传递给基类构造函数来设置字符串成员变量。
标签: c++ templates derived-class