看到下面的代码片段,我无法理解它是如何工作的。
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/