我有这个基类:
class BaseException { public: BaseException(string _message) { m_message = _message; } string GetErrorMessage() const { return m_message; } protected: string m_message; };
和这个派生类
class Win32Exception : public BaseException { public: Win32Exception(string operation, int errCode, string sAdditionalInfo = "") { string message = ""; message += "Operation \"" + operation + "\" failed with error code "; message += std::to_string(errCode); if (!sAdditionalInfo.empty()) message += "\nAdditional info: " + sAdditionalInfo; BaseException(message); } };
编译器给我以下错误:
错误C2512:'BaseException':没有合适的默认构造函数可用
我知道我可以构建一个非常长的行来构造将在初始化列表中传递给基类的消息,但这种方式似乎更优雅.
我究竟做错了什么?
你可以用另一种方式放置相同的东西:
class Win32Exception : public BaseException { static string buildMessage(string operation, int errCode, string sAdditionalInfo) { string message ; message += "Operation \"" + operation + "\" failed with error code "; message += std::to_string(errCode); if (!sAdditionalInfo.empty()) message += "\nAdditional info: " + sAdditionalInfo; return message; } public: Win32Exception(string operation, int errCode, string sAdditionalInfo = "") : BaseException(buildMessage(operation, errCode, sAdditionalInfo ) { } };