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

关于<<重载问题

mfkpgfsbihc 发布于 2007-12-01 17:09, 654 次点击
在ry.h中有如下声明:
#ifndef TIME_H
#define TIME_H
class Time{
private:
      int hours;
      int minuets;
public:
     Time();
     Time(int h,int m=0);
     void addMin(int m);
     void addHr(int h);
     void reset(int h=0,int m=0);
     Time operator+(const Time& t)const;
     Time operator-(const Time& t)const;
     Time operator*(double n)const;
     friend ostream& operator<<(ostream &os,const Time &t);
    // void show()const;
};
#endif
其定义在ry.cpp中,如下:
#include"ry.h"
//#include<iostream>
Time::Time(){
    hours=0;
    minuets=0;
}
Time::Time(int h,int m){
    hours=h;
    minuets=m;
}
void Time::addMin(int m){
     minuets+=m;
    hours+=minuets/60;
    minuets%=60;
}
void Time::addHr(int h){
    hours+=h;
}
void Time::reset(int h,int m){
     hours=h;
     minuets=m;
}
Time Time::operator+(const Time &t)const{
     Time sum;
     sum.minuets=minuets+t.minuets;
     sum.hours=hours+t.hours+sum.minuets/60;
     sum.minuets%=60;
     return sum;
}
Time Time::operator-(const Time &t)const{
      Time diff;
      int total1=minuets+60*hours;
      int total2=t.minuets+60*t.hours;
      diff.minuets=(total1-total2)%60;
      diff.hours=(total1-total2)/60;
      return diff;
}
Time Time::operator*(double n)const{
       Time t;
       t.minuets=(int)(minuets*n);
       t.hours=(int)(hours*n)+t.minuets/60;
       t.minuets%=60;
       return t;
}
ostream & operator<<(ostream &os,const Time &t){
     os<<"hours:"<<hours<<"\n"<<"minuets:"<<minuets<<endl;
    return os;
}
/*
void Time::show()const{
std::cout<<"hours:"<<hours<<std::endl;
std::cout<<"minuets:"<<minuets<<std::endl;
}*/
我实在不知道这个该怎么措词,望各位弄到你们机子上运行一下就明白了,我运行这几个错误就是不知道是什么原因造成的
yntax error : missing ';' before '&'
F:\程序设计\ry.cpp(52) : error C2501: 'ostream' : missing storage-class or type specifiers
F:\程序设计\ry.cpp(52) : error C2061: syntax error : identifier 'ostream'
F:\程序设计\ry.cpp(52) : error C2501: '<<' : missing storage-class or type specifiers
F:\程序设计\ry.cpp(52) : error C2809: 'operator <<' has no formal parameters
F:\程序设计\ry.cpp(53) : error C2065: 'os' : undeclared identifier
F:\程序设计\ry.cpp(53) : error C2297: '<<' : illegal, right operand has type 'char [7]'
F:\程序设计\ry.cpp(53) : error C2065: 'hours' : undeclared identifier
F:\程序设计\ry.cpp(53) : error C2065: 'minuets' : undeclared identifier
Error executing cl.exe.
4 回复
#2
中学者2007-12-01 17:14
重载右移要声明为友元~
#3
mfkpgfsbihc2007-12-01 17:21
我已经声明为友无了啊.
friend ostream& operator<<(ostream &os,const Time &t);
#4
中学者2007-12-01 17:24
ry.h里面没有包含<iostream>
#5
mfkpgfsbihc2007-12-01 17:37
谢,解决之
1