码迷,mamicode.com
首页 > 编程语言 > 详细

C++第五天笔记2016年02月22日(周一)P.M

时间:2016-02-25 22:43:57      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

1.    输出运算符重载:

 1 #include <iostream>
 2 #include"cstring"
 3 
 4 using namespace std;
 5 
 6 class Complex
 7 {
 8 public:
 9     Complex(int r=0,int i=0):_r(r),_i(i){}
10     void print();
11     friend ostream& operator<<(ostream& out,const Complex& _c);
12 private:
13     int _r;
14     int _i;
15 };
16 
17 ostream& operator<<(ostream& out,const Complex& _c){
18     out<<"_r="<<_c._r<<" _i="<<_c._i<<endl;
19     return out;
20 }
21 //cout<<c<<2  数据放入至cout缓存区  ostream  printf istream:cin
22 
23 //返回值类型不能加const修饰  通常使用友元
24 
25 //返回值为什么使用&:ostream类仅且仅有一个对象。
26 
27 //返回值为什么不能加const修饰:cout<<c1<<c2
28 //如果返回值被const修饰,则不能继续向cout中写入待输出数据 。
29 //Eg:  cout<<c;           //right
30 //     cout<<c<<endl;     //error
31 
32 //第二个参数:const& 既可以接收const对象,也可以接收非const对象。
33 //不能以成员函数的形式存在,因为第一个操作数只能是ostream类型唯一对象cout,不能为自定义类型的对象。
34 void Complex::print()
35 {
36     if (_i==0) {
37         cout<<_r<<endl;
38     }
39     else if(_i<0){
40         cout<<_r<<_i<<"i"<<endl;
41     }
42     else
43         cout<<_r<<"+"<<_i<<"i"<<endl;
44 }
45 int main(int argc, const char * argv[]) {
46     cout<<"C1=";
47     Complex c1(3,2);
48     c1.print();
49     cout<<c1;
50     return 0;
51 }

2. 下标运算符重载:

 1 #include <iostream>
 2 #include "cstring"
 3 #define size 5
 4 using namespace std;
 5 
 6 class Vector
 7 {
 8 public:
 9     const int & operator[](int index)const//const版本:侧重于读取元素的值
10     {
11         return rep[index];
12     }
13     int & operator[](int index)//非const版本:侧重于写入、修改元素的值
14     {
15         return rep[index];
16     }
17 private:
18     int rep[size];//返回值类型:容器中的元素类型。
19 };
20 
21 ostream& operator<<(ostream& out,const Vector& a)
22 {
23     for (int i=0; i<size; i++) {
24         out<<a[i]<<" ";//使用const版本 编译器会调用下标重载函数。
25     }
26     return out;
27 }
28 
29 
30 int main(int argc, const char * argv[]) {
31     Vector x;
32     cout<<"Enter "<<size<<" integers.\n";
33     for (int i=0; i<size; i++) {
34         cin>>x[i];
35     }
36     const Vector y=x;
37     cout<<"x:"<<x<<endl;
38     cout<<"y:"<<y<<endl;
39     x[0]=100;
40     cout<<"x:"<<x<<endl;
41     cout<<"y:"<<y<<endl;
42     return 0;
43 }

 

C++第五天笔记2016年02月22日(周一)P.M

标签:

原文地址:http://www.cnblogs.com/cai1432452416/p/5218497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!