簡體   English   中英

在派生類的構造函數的主體中調用基本構造函數

[英]Calling base constructor in body of derived class' constructor

我有這個基類:

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 )
    {
    }
};

您必須在構造函數的成員初始化程序列表中進行基類的“構造”,而不必在派生類的構造函數的主體中“調用”基類的構造函數。

這意味着,而不是

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;
     }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM