我有这个基类:
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' :没有合适的默认构造函数
我知道我可以构建一个非常长的行来构造将在初始化列表中传递给基类的消息,但这样看起来更优雅。
我做错了什么?
答案 0 :(得分:5)
你可以用另一种方式放置相同的东西:
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 )
{
}
};
答案 1 :(得分:3)
你必须在构造函数的 member initializer list 中进行基类的“构造”,而不是“调用”体系中基类的构造函数。派生类的构造函数。
这意味着,而不是
Win32Exception(string operation, int errCode, string sAdditionalInfo = "")
{
.....
BaseException(message);
}
你必须
Win32Exception(string operation, int errCode, string sAdditionalInfo = "")
: BaseException("")
{
.....
}
错误消息
错误C2512:'BaseException':没有合适的默认构造函数
表示您没有在成员初始值设定项列表中定义基类BaseException
的构造,但BaseException
没有默认构造函数。
简单地说,编译器没有我不知道该怎么做,因为没有说明应该如何构建基类。
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 = "")
: BaseException("")
{
string message = "";
message += "Operation \"" + operation + "\" failed with error code ";
message += std::to_string(errCode);
if (!sAdditionalInfo.empty())
message += "\nAdditional info: " + sAdditionalInfo;
m_message = message;
}
};