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

lja*_*son 2 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;
}
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 6

您需要创建temp_obj并返回它,就像在postfix中一样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
}
Run Code Online (Sandbox Code Playgroud)

  • 添加马特的观点.有些地方你使用小时/ 8和其他小时/ 8.0你会遇到奇怪的不一致.你的意见也是错的.`numDays operator ++(int)`是post-fix运算符.代码看起来正确.评论错了. (2认同)