【问题标题】:What is the use of a private init() member function?私有 init() 成员函数有什么用?
【发布时间】: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


【解决方案1】:

这是一种古老的 C++ 风格。它允许多个构造函数共享代码。

现代 C++ 会使用

Time::Time() : Time(0,0,0) { }

它重用了现有的 3 参数 ctor。

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多