首页 技术 正文
技术 2022年11月9日
0 收藏 990 点赞 2,460 浏览 1240 个字

1. 问题

  在C++中,在进行输入输出操作时,我们首先会想到用cout, cin这两个库操作语句来实现,比如

    cout << 8 << “hello world!” << endl;

    cin >> s;

  cout,cin分别是库ostream, istream里的类对象

  如果想要cout,cin来输出或输入一个类对象,这样的需求它能满足吗?很显然,原来的cout不太可能满足直接输入输出一个我们自定义的类对象,

  但是只要我们对<<, >>操作符进行重载就可以让它处理自定义的类对象了。

2. 实现

  有一复数类:

class Complex {
priate:
int real;
int imag;
public:
Complex(int r=, int i=):real(r),imag(i) {
cout << real << " + " << imag << "i" ;
cout << "complex class constructed."
}
}

int main() {
      Complex c; // output : 0+0i, complex class constructed.
      cout << c ; // error

return 0;
}

  之所以上面main函数中 cout << c会出错,是因为 cout本身不支持类对象的处理,如果要让它同样能打印类对象,必须得重载操作符<<.

#include <iostream>
#include <string>class Complex {
priate:
int real;
int imag;
public:
Complex(int r=, int i=):real(r),imag(i) {
cout << real << " + " << imag << "i" ;
cout << "complex class constructed."
}
// overload global function
friend ostream & operator<<(ostream & o, const Complex & c);
friend istream & operator >> (istream & i, Complex & c);
}ostream & operator<<(ostream & o, const Complex & c) {
o<< c.real << "+" << c.imag << "i";
return o;
}istream & operator >> (istream & i, Complex & c){
string s;
i >> s; // simillar to cin >> s; input string format like as a+bi
... // parse s and get the real and imag
c. real = real;
c.imag = imag;
return i;
}

  重载了操作符 <<, >> 运算后, 就可以对类Complex直接进行 输入输出操作了,比如

int main{
Complex c, c1;
cin >> c; //input : 3+4i
cout << c <<";" << c1 << " complex output."; // output : 3+4i; 0+0i complex output.
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295