c++ - 在 C++ 中重载输入/输出运算符
问题描述
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
**friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);**
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
将运算符作为参考“& 运算符”传递有什么用。当我们传递一个普通的操作符时,我们从不传递引用,但是在上面的代码中,我们将引用传递给了操作符。谁能解释传递操作员参考的部分?
解决方案
在代码friend ostream & operator <<
中&
,与重载运算符返回的类型相关联。这样它就会返回ostream &
并返回istream &
第二个。
重载的运算符:
- 获取对 I/O 对象的引用
istream
或ostream
对象,例如用于控制台 I/O 的 cin/cout 或其他类型的流对象(来自/到字符串的 I/O 等)。 - 影响对象的状态,以便读取/写入数据。
返回对该对象的引用,以便您可以按顺序使用这些运算符,例如:
Complex c1 Complex c2; cin >> c1 >> c2;
推荐阅读
- javascript - 隐藏和显示svg的最简单方法?
- python - 无头硒突然停止工作
- asp.net-mvc - 使用 Simple Injector 注册单个类
- angular - 角度错误:没有 NgControl 的提供者
- python - 在 Web App 中设置 Bokeh Charts 的绝对屏幕位置
- android - 更新 gradle 插件后,Android Studio 无法构建我的应用程序
- aws-appsync - 如何使用 amplify 从 aws schema.graphql 生成 graphql 语句
- python - 当键值相同时如何将数据附加到python dict中?
- java - Eclipse 无法识别生成的类
- r - R从数据框中的列和行中提取值