重载+运算符问题与其他类中的友元函数混合

时间:2017-10-21 09:10:54

标签: c++

#include <iostream>
#include "NumDays.h"
#include "Overtime.h"
#include <math.h>
using namespace std;

NumDays::NumDays(double hourss)
{

    if(hourss > 0)
    {
        hours = hourss;
    }
    else
    {
        cout << endl << "Invalid number given.";
        cout << endl << "Hours set to 0." << endl;
        hours = 0.00;
    }

}


NumDays operator + (const NumDays& right)
{
    NumDays temp;

    temp.hours = this->hours + right.hours;
    return temp;
}
#ifndef NUMDAYS_H
#define NUMDAYS_H
#include "Overtime.h"

class Overtime;

class NumDays
{
    friend class Overtime;

    private:
        //double hours = 0.00;
        int days = 0;
        friend void setHoursOT(NumDays&, Overtime&);



    public:
        double hours = 0.00;
        NumDays();
        NumDays(double hourss);
        void getTime();
        double getHours() {return hours;}
        void setHours(double);


        //Overloaded operators
        NumDays operator + (const NumDays&);
        NumDays operator - (const NumDays&);
};


#endif
#ifndef OVERTIME_H
#define OVERTIME_H
#include "NumDays.h"

class NumDays;

class Overtime
{


    private:
        double hours2 = 0.00;
        friend void setHours(NumDays&, Overtime&);



    public:
        Overtime(double hourz);


};
#endif

每次编译它都不会让我完成。我需要有一个重载的运算符,但我在+运算符 - 运算符和其他一些运算符上尝试它时遇到了同样的问题。它会弹出实现文件的第50行,其中显示“temp1 = this.hours + rhs.hours;”并说每次都有问题。此外,它有时会弹出其他变体这样做,说加班中的小时2是私人的,或者NumDays类中的小时是私人的,不会让我做任何事情。我从6小时前开始使用google搜索,发现了一些最终让我无处可寻的东西。我发现的最常见的解决方案包括NumDays NumDays :: operator +(const NumDays&amp; lhs,const NumDays&amp; rhs),并以这种方式添加它们,但即使我这样做,它在第50行也提供了相同的错误我试过这个 - &gt;,这个。 *这个。 *这 - &GT;等没有骰子。

 I've also tried doing it without the Overtime.h/Overtime.cpp and nothing related to that file in there and it ends up saying returned 1 exit status.  Everything works but the overloaded functions and I just can't find where I'm messing up.

1 个答案:

答案 0 :(得分:1)

this是指针,不是引用,因此您应该编写temp1 = this->hours + rhs.hours;而不是temp1 = this.hours + rhs.hours;

这很可能是你得到的错误&#34;第50行&#34;当你举报时。

此外:

  • 您的operator-被声明为内部,但实施为外部。
  • 您的operator-实施没有意义。 double没有hours属性...

我建议您首先使用operator +,使其工作,然后再实现operator-。看起来你在第一次尝试编译之前编写了很多代码,这对初学者来说不是一个好的策略,每次添加新函数时编译,然后你就会更容易发现编译器报告的错误。来自。

正确实施将是:

NumDays NumDays::operator+(const NumDays& right)
{
    NumDays temp;
    temp.hours = this->hours + right.hours;
    return temp;
}

NumDays NumDays::operator+(const NumDays& right)
{
    double temp;
    temp = this->hours + right.hours;
    return NumDays(temp);
}
相关问题