【发布时间】:2022-11-19 01:27:11
【问题描述】:
假设我有课时间:
class Time {
public:
Time();
Time(int hours, int mins, int secs);
// public member functions here
friend std::ostream& operator << (std::ostream&, Time&);
private:
int theHour;
int theMins;
int theSecs;
void init(int hours, int minutes, int seconds);
};
我知道在设置 hours = theHour, mins = theMins, secs = theSecs 之前根据小时/分钟/秒值创建 Time 对象时我必须做的一件事是检查小时/分钟/秒的值是否有效。但是,我已经有一个构造函数Time(int hours, int mins, int secs);,我正在考虑定义如下:
Time::Time(int hours, int mins, int secs)
{
if ((hours < 0) || (mins < 0) || (secs < 0) || (hours > 60) || (mins > 60) || (secs > 60))
{
cout << "Illegal time value.\n";
exit(1)
}
hours = theHour;
mins = theMins;
secs = theSecs;
}
如果我已经有一个构造函数来将小时、分钟、秒的实例初始化为时间对象并检查非法值,那么 void init() 函数的意义何在?
【问题讨论】:
-
与其使用 xit(1) 这是一种非常粗鲁的终止进程的方式,不如考虑抛出 std::invalid_argument。 private init 是一种为各种构造函数提供可重用代码的方法。但是,您确实应该为此使用构造函数委托。
-
我不明白,你写了
init函数,现在你不需要它了?
标签: c++ class constructor initialization private