C ++ - 重载运算符+接受一个参数

时间:2015-02-26 22:58:27

标签: c++

完成任务并完成几乎所有工作,但我似乎无法列出该课程的操作符+ 功能。指导/指导将非常受欢迎,因为我似乎无法确定我做错了什么。

#include <iostream>

using namespace std;

class numDays {

private: // member variables
    int hours;
    double days;

public: // member functions

    numDays(int h = 0) {
        hours = h;
        days = h / 8;
    }

    void setHours(int s) {
        hours = s;
        days = s / 8;
    }

    double getDays() {
        return days;
    }

    numDays operator+(numDays& obj) {
        // what to put here?
    }

    numDays operator- (numDays& obj) { // Overloaded subtraction
        // and here?
    }

    numDays operator++ () { // Overloaded postfix increment
        hours++;
        days = hours / 8.0;
        numDays temp_obj(hours);
        return temp_obj;
    }

    numDays operator++ (int) { // Overloaded prefix increment
        numDays temp_obj(hours);
        hours++;
        days = hours / 8.0;
        return temp_obj;
    }

    numDays operator-- () { // Overloaded postfix decrement
        hours--;
        days = hours / 8.0;
        numDays temp_obj(hours);
        return temp_obj;
    }

    numDays operator-- (int) { // Overloaded prefix decrement
        numDays temp_obj(hours);
        hours--;
        days = hours / 8.0;
        return temp_obj;
    }
};


int main() {
    // insert code here...
    numDays one(25), two(15), three, four;

    // Display one and two.
    cout << "One: " << one.getDays() << endl;
    cout << "Two: " << two.getDays() << endl;

    // Add one and two, assign result to three.
    three = one + two;

    // Display three.
    cout << "Three: " << three.getDays() << endl;

    // Postfix increment...
    four = three++;
    cout << "Four = Three++: " << four.getDays() << endl;

    // Prefix increment...
    four = ++three;
    cout << "Four = ++Three: " << four.getDays() << endl;

    // Postfix decrement...
    four = three--;
    cout << "Four = Three--: " << four.getDays() << endl;

    // Prefix increment...
    four = --three;
    cout << "Four = --Three: " << four.getDays() << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:6)

您需要制作一个temp_obj并将其返回,就像您在后缀operator++中一样,但是您将更新temp_obj的成员,而不是更新this中的任何内容}。

实际上,您可以将其设为const成员函数,以便编译器检测您是否意外更新了this。大多数人甚至使用operator+的非成员运算符重载来使其成为对称关系。


无关,但是:

  • days = h / 8;是整数除法(余数被丢弃)
  • 您的代码似乎并行维护dayshours,这很脆弱。似乎只有hours应该是成员变量,而getDays函数(应该是const)可以动态计算它。
  • 正如Dan Allen所指出的,前缀operator++operator--(其中没有伪参数)不应该按值返回 - 这些函数应该更新this成员并返回对*this
  • 的引用

专业提示:为避免代码重复,您可以像这样执行增量运算符(假设您希望它们都是成员函数):

numDays & operator++()          // prefix
{
    // your logic here, e.g. hours++;
    return *this;
}

numDays operator++(int dummy)   // postfix
{
     return ++numDays(*this);   // invokes prefix operator++ we already wrote
}