C++ - 为什么我可以返回类Month的int

q09*_*987 4 c++

看到以下代码片段,我有问题了解它是如何工作的.

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;
}
Run Code Online (Sandbox Code Playgroud)

该类以这种方式设计,以便用户不会获得无效的月份值.

这是一个问题:为什么静态函数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;
};
Run Code Online (Sandbox Code Playgroud)

Did*_*set 12

Month对象正在使用的自动创建的Month(int)构造函数.它应该/应该以这种方式写成明确的:

static const Month Jan() { return Month(1); }
Run Code Online (Sandbox Code Playgroud)

请注意,良好的做法是声明将一个参数作为的构造函数explicit.实际上,正如您对代码所经历的那样,这些构造函数可用于执行类型转换.好的做法是明确声明这些构造函数,以便不会发生这种自动转换.它会强迫你像我一样写它.

  • `Month(int number)`构造函数也可以是`explicit`.一般来说,最好将所有ctors用单个变量标记为"explicit"(除了复制文件). (2认同)