重载<<的输出不正确operator c ++

时间:2016-04-26 21:17:38

标签: c++ class c++11 constructor operator-overloading

我显示Class NumDays

Class NumDays
{
   private:
      double hours;

   public:
      NumDays() { hours = 0.0; }            //default constructor
      NumDays(double hr) { hr = hours; }    //initializing constructor  

   //Large class, nothing of importance, rest of class omitted

   //overloading << operator
    friend ostream &operator<<(ostream &out, NumDays a);
}

我有NumDay.cpp,其中包括:

ostream &operator<<(ostream& out, NumDays a)
{
   // takes amount of hours, computes to work days

   int temp = a.hours / 8;

   //gives remainder of hours after full 8 hr workday.

   double hrs = a.hours - (temp * 8);

   //outputs 
   cout << fixed << setprecision(0);
   out << (a.hours / 8) << " Days, " << hrs << "hours";
    return out;
}

我有main.cpp包括:

int main()
{
   // Initialized UDT object Declarations
   NumDays hoursWorked_John;       // Instantiate with Default Constructor
   NumDays hoursWorked_Sue(36.9);  // Instantiate with Initializing Cons      
   NumDays hoursUsed_Sue(4.5);     // Instantiate with Initializing Cons

   cout << "John's initial hours worked: " << hoursWorked_John << endl;
   hoursWorked_John.addHours(56.78);
   cout << "  John's final hours worked: " << hoursWorked_John << endl;

   cout << "Sue's initial hours worked: " << hoursWorked_Sue << endl;

   //rest of main omitted for sake of size

当我去运行程序的这一小部分时,这是我的控制台:

Consle Output

任何关于为什么苏小时如此错误的想法,但约翰是正确的?

3 个答案:

答案 0 :(得分:7)

  NumDays(double hr) { hr = hours; }    //initializing constructor  

糟糕。在这里,您将成员hours保持未初始化状态,并修改临时参数hr。你似乎意味着

  NumDays(double hr) { hours = hr; }

(或者更好:):

  NumDays(double hr) : hours(hr) {}

答案 1 :(得分:2)

NumDays(double hr) { hr = hours; }

应该是

NumDays(double hr) { hours = hr; }

答案 2 :(得分:0)

问题是您打印垃圾值,因为您的运营商<<会调用NumDays的{​​{1}}默认值{。}}。

NumDays(const NumDays& other){
}

这意味着您不打印之前已初始化的对象。
解决方案:
按如下方式更改运算符原型:

/*  change NumDays a to const NumDays& a 
 *  a must not be modified by this operator (const).
 *  a must be passed by reference (NumDays&) to avoid duplications (copy constructor)
 */
ostream &operator<<(ostream& out,const NumDays & a)
{
   int days = a.hours/8.f;
   streamsize old_precision = out.precision(0);
   ios_base::fmtflags old_flags = out.flags();
   out <<fixed<< days << " Days, " << (a.hours - days*8.f)  << " hours";
   out.precision(old_precision);//restore old precision
   out.flags(old_flags);//restore old format flags
   return out;
}

您的操作员<<原型只有在copy constructor像这样重载时才能工作:

NumDays(const NumDays& other){
    hours = other.hours;
}

我认为你不需要double精确float就足够了
经过测试:g++ (Debian 4.9.2-10) 4.9.2