在C++中重载输入/输出运算符
Overloading input/output operators in 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 &
。
重载运算符:
- 引用
istream
或ostream
对象,该对象是 I/O 对象,例如控制台 I/O 的 cin/cout 或其他类型的流对象(来自/到字符串的 I/O 等(。 - 影响对象的状态,以便读取/写入数据。
-
返回对该对象的引用,以便可以按顺序使用这些运算符,如下所示:
Complex c1 Complex c2; cin >> c1 >> c2;
通常,如果遵守每个声明声明一个名称(仅(规则, 然后,这允许在类型旁边一致地编写一个指针/引用"卡住"为:
istream& operator>> (istream& in, Complex& c)
{ //...
通过这种方式,可以看出名为operator>>
的函数正在返回一个类型istream&
(对 istream 对象的引用(。
此函数采用 2 个变量:
istream&
类型(对 istream 对象的引用(的in
,Complex&
类型(对复杂对象的引用(的c
。
同样适用于:
ostream& operator<< (ostream& out, const Complex& c)
{ //...
代码的格式无论如何都不会影响代码的编译方式。 所以这个答案中的函数定义与问题中的函数定义完全相同。
至于为什么要使用引用,我建议阅读:何时使用引用与指针
相关文章:
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 在C++中重载输入/输出运算符
- 如何处理自定义输出运算符中的 iomanips?
- 基于对函数的参数调用流输出运算符的能力重载函数
- C++将 toString 替换为重载的输出运算符
- 尝试过载输出运算符时出错
- 重载输出运算符给出十六进制数字而不是字符串
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- Qt 使用迭代器重载了 qtextstream 输出运算符
- 抽象类和派生类的输出运算符 (<<)
- 重载输出运算符和后置增量运算符时"运算符<<"错误不匹配
- 如何在输出运算符中测试std::showbase或std::noshowbase
- 队列类C++的输出运算符重载
- 变量类型和变量模板的转换和输出运算符
- 重载输出运算符<<以使用 STL 列表迭代器
- C++抽象类的输出运算符
- 重载基类及其派生类(C++)的输出运算符
- 重载输出运算符时出现错误
- 为什么我的输出运算符 <<() 函数定义会导致无法解析的外部符号错误?