簡體   English   中英

C ++ - 為什么我可以返回類Month的int

[英]C++ — Why I can return an int for class Month

看到以下代碼片段,我有問題了解它是如何工作的。

class Month {
public:
    static const Month Jan() { return 1; }
    ...
    static const Month Dec() { return 12; }

    int asInt() const { return monthNumber; }
private:
    Month(int number) : monthNumber(number) {}
    const int monthNumber;
}

該類以這種方式設計,以便用戶不會獲得無效的月份值。

這是一個問題:為什么靜態函數Jan可以返回1,返回值為Month?

謝謝

根據評論,這個類可以設計如下:

class Month {
public:
    static const Month Jan() { return Month(1); }
    ...
    static const Month Dec() { return Month(12); }

    int asInt() const { return monthNumber; }
private:
    explicit Month(int number) : monthNumber(number) {}
    const int monthNumber;
};

Month對象是使用Month(int)構造函數自動創建的。 它應該/應該以這種方式寫成明確的:

static const Month Jan() { return Month(1); }

請注意,良好的做法是聲明將一個參數視為explicit構造explicit 實際上,正如您對代碼所經歷的那樣,這些構造函數可用於執行類型轉換。 好的做法是明確聲明這些構造函數,以便不會發生這種自動轉換。 它會強迫你像我一樣寫它。

因為您沒有將構造函數標記為“顯式”,所以它可以在隱式轉換操作中使用。

我認為構造函數正在隱式轉換中使用。

IE瀏覽器。 構造函數可以從整數創建Month對象。 編譯器自動使用它來創建要返回的Month對象。

我認為這是不好的做法,許多編譯器應該發出警告。 如果這是為您編譯的,請嘗試更改編譯器警告級別,以使其更嚴格。

你的構造函數是私有的。 如果您希望能夠使用int構造Month實例,則必須將該構造函數聲明為public

暫無
暫無

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

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