关于<<重载和友元

lhw7791086 2014-03-13 05:22:55

#include <iostream>
using namespace std;

class time
{
private:
int hour;
int minute;
public:
time();
time(int h,int m){hour=h;minute=m;}
time operator+(const time& t);
time operator-(const time& t);
time operator*(const double d);
friend time operator*(const double d,time& t);
friend ostream& operator<<(ostream& os,const time& t);
};
//省略其他函数定义......
ostream& operator<<(ostream& os,const time& t)
{
os<<t.hour<<":"<<t.minute;
return os;
}

在这里报错:
ostream& operator<<(ostream& os,const time& t)
{
os<<t.hour<<":"<<t.minute;
return os;
}运行后报错:error C2248: 'hour' : cannot access private member declared in class 'time'
error C2248: 'minute' : cannot access private member declared in class 'time'
我本想重载<<运算符的非成员函数版本,于是使用友元,为什么还是提示我无法调用私有变量成员?前几天同样方式写代码都没问题,不知道这次问题出现在哪里?求教。
...全文
182 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lhw7791086 2014-03-13
  • 打赏
  • 举报
回复
引用 2 楼 a345485527 的回复:
1.lz的编译器要是vc6就换掉,这个对友元支持不好 2.把time改成Time 3.time(); 这个构造函数没有实现
已解决,代码在VS08,VS10或者VC08下可运行
mujiok2003 2014-03-13
  • 打赏
  • 举报
回复
怀疑你的名字空间
#include <iostream>
using namespace std;
namespace COM
{
class Time
{
private:
    int hour;
    int minute;
public:
    Time(){}
    Time(int h,int m){hour=h;minute=m;}
    Time operator+(const Time& t);
    Time operator-(const Time& t);
    Time operator*(const double d);
    friend Time operator*(const double d,Time & t);
    friend ostream& operator<<(ostream& os,const Time& t);
};
//make it as a member of namespace 
ostream& operator<<(ostream& os,const COM::Time& t)
{
    os<<t.hour<<":"<<t.minute;
    return os;
}

}//end of namespace COM

int main()
{
  COM::Time t;
  std::cout << t << std::endl;
  return 0;
}
u011043553 2014-03-13
  • 打赏
  • 举报
回复
好奇一下friend bool operator <(const point &a,const point &b);
buyong 2014-03-13
  • 打赏
  • 举报
回复
把友元写在类的开头
Pump天天学习 2014-03-13
  • 打赏
  • 举报
回复
1.lz的编译器要是vc6就换掉,这个对友元支持不好 2.把time改成Time 3.time(); 这个构造函数没有实现
PDD123 2014-03-13
  • 打赏
  • 举报
回复
我几乎没有用过“<<”作为输入的运算符,但是我想是不是原版的<<运算符无法访问私有成员?

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧