C++——为什么我可以为类 Month 返回一个 int

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

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

问题如下: 为什么静态函数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。事实上,这些构造函数可用于执行类型转换,正如您在代码中所体验到的那样。好的做法是显式声明这些构造函数,这样就不会发生这种自动转换。它会迫使你像我一样写。

关于C++——为什么我可以为类 Month 返回一个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027986/

相关文章:

c++ - 在更多 C++ 编译器/平台上调用 FINGERPRINT_premain

c++ - 调用返回表的lua函数

c++ - "Inline"带有初始化列表的对象的静态声明

c++ - Boost ASIO SSL 握手失败

c++ - delete[]指针起作用的时候,为什么获取不到指向的数组的大小呢?

c++ - .data() 等效于 std::queue

c++ - 映射和迭代器(in)验证

c++ - 等价于 C++ 中来自 Java 的枚举的 .values()

c++ - 将 double 降级为 float 时没有警告

c++ - 如何使用opencv在ios中写一个简单的图片加载函数