重载+运算符以使用int添加对象

时间:2018-03-06 21:18:49

标签: c++

我刚刚学会了操作员重载,而我在重载' +' operator用int添加对象。我也不确定如何超载'<<<&#输出一个对象。

非常感谢任何建议或帮助。

#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

class CLOCK
{
public:
    int h, m, s;
    CLOCK()
    {
        h = 0;
        m = 0;
        s = 0;
    }
    CLOCK(int hour, int minute, int second)
    {
        hour = h;
        minute = m;
        second = s;
    }

    CLOCK operator+(int time)
    {
        CLOCK c(*this);
        c.m += time;
        return c;
    }

    CLOCK operator++(int)
    {
        CLOCK c(h,m,s);
        h++;
        return c;
    }
    friend ostream &operator<<(ostream &output, const CLOCK &c)
    {
        output << c.h << c.m << c.s << endl;
        return output;
    }
};

int main()

{

    CLOCK c(10, 10, 10);

    cout << c << endl; // should display 101010

    c = c + 10; // should display 10 minutes to my clock

    cout << c.hour << c.minute << c.second << endl;  // should display 102010

    c++; // this should increment hours, time now is 012010
    system("pause");
}

1 个答案:

答案 0 :(得分:6)

您的主要问题不是运算符重载(看起来没问题)。这是你的构造函数严重错误

CLOCK(int hour, int minute, int second)
{
    hour = h;
    minute = m;
    second = s;
}

应该是这个

CLOCK(int hour, int minute, int second)
{
    h = hour;
    m = minute;
    s = second;
}

理想情况下,您可以使用member initializer list,这会在编译期间遇到向后分配的错误。形成也是一个好习惯:

CLOCK(int hour, int minute, int second)
    : h(hour), m(minute), s(second)
{
}

如果那些已经倒退,(hour(h)等),编译器会呕吐并告诉你,然后你做的不对。