【问题标题】:operator overloading >> and private member [duplicate]运算符重载>>和私有成员[重复]
【发布时间】:2013-07-10 15:06:19
【问题描述】:

请在标记为重复之前阅读

我正在重载运算符 >> 和

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class complex
{
    int r,i;
public:
complex()
{ i=r=0;}
friend istream& operator>>(istream&, complex&);
friend ostream& operator<<(ostream&,complex&);
};
istream& operator>>(ifstream &din, complex &x)
{
    din>>x.r;
    din>>x.i;
    return din;
}
ostream& operator<<(ostream &dout, complex &x)
{
dout<<x.r<<x.i;
return dout;
}
void main()
{
clrscr();
complex x;
cin>>x;
cout<<x;

}

错误是 r 和 i 不可访问 在代码部分

din>>x.r; din>>x.i;

错误是 r 和 i 是私有的,因此无法访问 普通的朋友函数不能访问私有变量。为什么它只对 >> 失败?

注意:> 失败

【问题讨论】:

  • 请不要以这种方式设计您的课程。会很混乱。
  • iostream.h 不是标准标头。使用iostream。标准 C++ 头文件都没有扩展。 void main 也不是合法签名。使用int main

标签: c++ operator-overloading cin private-members friend-function


【解决方案1】:

operator&gt;&gt; 的friend 声明采用istream 参数,但实现采用ifstream 参数,使其成为完全不同的(因此非friend)函数。删除多余的f,它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多