注册 登录
编程论坛 C++教室

请问这错误怎么回事?

a99875984 发布于 2012-06-12 15:07, 369 次点击
程序代码:
#include<iostream>
using namespace std;
class time
{
private:
    int h,m,s;
public:
    time (int a,int b,int c);
    void operator +(time t1);
    void operator -(time t1);
    void shuchu();
};

time::time(int a,int b,int c)
{
    h=a;
    m=b;
    s=c;
    cout<<h<<":"<<m<<":"<<s<<endl;
}

void  time::operator +(time t1)
{
    s=s+t1.s;
    if(s>=60)
    {
        s-=60;
        m++;
    }
    m=m+t1.m;
    if(m>=60)
    {
        m-=60;
        h++;
    }
    h=h+t1.h;
}
void time::operator -(time t1)
{
    s=s+t1.s;
    if(s<0)
    {
        s+=60;
        m--;
    }
    m=m+t1.m;
    if(m<0)
    {
        m+=60;
        h--;
    }
    h=h+t1.h;
}

void time::shuchu()
{
    cout<<h<<":"<<m<<":"<<s<<endl;
}
int main()
{
    int a,b,c,d,e,f;
    cin>>a>>b>>c>>d>>e>>f;
    time t1(a,b,c),t2(d,e,f),t3(0,0,0);
    t3=t1+t2;        //no operator defined which takes a right-hand operand of type 'void' (or there is no acceptable conversion)  这是什么意思啊?
    t3.shuchu();
    return 0;
}
3 回复
#2
zxwangyun2012-06-12 15:39
time &operator +(const time &t1);

time &time::operator +(const time &t1)
{
    s=s+t1.s;
    if(s>=60)
    {
        s-=60;
        m++;
    }
    m=m+t1.m;
    if(m>=60)
    {
        m-=60;
        h++;
    }
    h=h+t1.h;
    return *this;
}
#3
zxwangyun2012-06-12 15:41
但是这样定义下来后,+ 其实相当于 += 了
如果你硬是要这么做的话,重新定义一个函数来实现 + 吧
#4
lonmaor2012-06-12 17:10
程序代码:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

class Time
{
public:
    Time(int h, int m, int s):hour(h),minute(m),second(s) {}
    friend Time operator+ (const Time& t1, const Time& t2) ;
//    friend Time operator- (const Time& t1, const Time& t2) ;
    void shuchu() const;
private:
    int hour;
    int minute;
    int second;
};

void Time::shuchu() const
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}

Time operator+ (const Time& t1, const Time& t2)
{
    Time t(0,0,0);
    t.second = t1.second + t2.second;
    if (t.second>=60)
    {
        t.minute++;
        t.second-=60;
    }

    t.minute += (t1.minute + t2.minute);
    if (t.minute>=60)
    {
        t.hour++;
        t.minute-=60;
    }

    t.hour += (t1.hour + t2.hour);
    return t;
}
//Time operator- (const Time& t1, const Time& t2) ;

int _tmain(int argc, _TCHAR* argv[])
{
    int a,b,c,d,e,f;
    cin>>a>>b>>c>>d>>e>>f;
    Time t1(a,b,c),t2(d,e,f),t3(0,0,0);
    t3 = t1+t2;
    t3.shuchu();
    return 0;
}
1