<<和>>重载必须申明为类的友元?

alwjuq 2009-12-08 12:37:54
我感觉可以不用申明为友元.

class A
{
private:
int x;
public:
A(int x_ = 0):x(x_) {}
void Print(void) const
{
cout << x << endl;
}
}

std::istream& operator << (std::ostream is,const Book& rhs)
{
rhs.Print();
return os;
}

我想的是尽量减少友元,但是好像行不通....
...全文
115 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
lovesi3344 2009-12-08
  • 打赏
  • 举报
回复
10个操作符不能重载
四个操作符只能用成员函数重载
其余操作符既可以用成员函数重载也可以用友元函数重载

10个操作符不能重载
有“点”的操作符四个
. ?: :: .*
与RTTI有关的操作符4个
typeid
const_cast<>()
dynamic_cast<>()
static_cast<>()
2个字母型的操作符
sizeof
typedef

四个操作符只能用成员函数重载
=
[]
()
->

eigar 2009-12-08
  • 打赏
  • 举报
回复
(1)只能使用成员函数重载的运算符有:=、()、[]、->、new、delete。

(2)单目运算符最好重载为成员函数。
(3) 对于复合的赋值运算符如+=、-=、*=、/=、&=、!=、~=、%=、>>=、<<=建议重载为成员函数。

4) 对于其它运算符,建议重载为友元函数。
alwjuq 2009-12-08
  • 打赏
  • 举报
回复
养成少用友元的好习惯....
taodm 2009-12-08
  • 打赏
  • 举报
回复
友元多一点或者少一点,有什么实际意义呢?就一个语法糖而已。
alwjuq 2009-12-08
  • 打赏
  • 举报
回复
的确错误很多....我在发帖窗口写的,没注意到...
mstlq 2009-12-08
  • 打赏
  • 举报
回复
当然可以不为友元了……
例子
#include<iostream>
#include<string>
using namespace std;
class Book
{
private:
int x;
public:
Book(int x_ = 0):x(x_) {}
void Print(std::ostream &os) const
{
os << x << endl;
}
};

std::ostream& operator << (std::ostream &os,const Book& rhs)
{
rhs.Print(os);
return os;
};
int main()
{
return 0;
}
hai040 2009-12-08
  • 打赏
  • 举报
回复
忘了引用
std::ostream& os
hai040 2009-12-08
  • 打赏
  • 举报
回复

class A
{
private:
int x;
public:
A(int x_ = 0):x(x_) {}
void Print(std::ostream os) const
{
os << x << endl;
}
}

std::ostream& operator << (std::ostream os,const Book& rhs)
{
rhs.Print(os);
return os;
}

不过一般是把print设为private
alwjuq 2009-12-08
  • 打赏
  • 举报
回复
应该怎么操作?
VeiwoZouhui 2009-12-08
  • 打赏
  • 举报
回复
不需要
lovesi3344 2009-12-08
  • 打赏
  • 举报
回复
帮你顶上去
alwjuq 2009-12-08
  • 打赏
  • 举报
回复

std::ostream& operator << (std::ostream is,const Book& rhs)
{
rhs.Print();
return os;
}


打错了,抱歉啊
macrojj 2009-12-08
  • 打赏
  • 举报
回复
本来就可以不重载
重载是为了访问私有变量
如果你有间接访问的函数,当然可以咯

64,662

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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