例9.1
完整实现str类的例子。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 #include <string> 5 6 using namespace std; 7 8 class str 9 { 10 private: 11 char *st; 12 public: 13 str(char *s);//使用字符指针的构造函数 14 str(str& s);//使用对象引用的构造函数 15 str& operator=(str& a);//重载使用对象引用的赋值运算符 16 str& operator=(char *s);//重载使用指针的赋值运算符 17 void print() 18 { 19 cout << st << endl;//输出字符串 20 } 21 ~str() 22 { 23 delete st; 24 } 25 }; 26 27 str::str(char *s) 28 { 29 st = new char[strlen(s) + 1];//为st申请内存 30 strcpy(st, s);//将字符串s复制到内存区st 31 } 32 33 str::str(str& a) 34 { 35 st = new char[strlen(a.st) + 1];//为st申请内存 36 strcpy(st, a.st);//将对象a的字符串复制到内存区st 37 } 38 39 str& str::operator=(str& a) 40 { 41 if (this == &a)//防止a=a这样的赋值 42 { 43 return *this;//a=a,退出 44 } 45 delete st;//不是自身,先释放内存空间 46 st = new char[strlen(a.st) + 1];//重新申请内测 47 strcpy(st, a.st);//将对象a的字符串复制到申请的内存区 48 return *this;//返回this指针指向的对象 49 } 50 51 str& str::operator=(char *s) 52 { 53 delete st;//是字符串直接赋值,先释放内存空间 54 st = new char[strlen(s) + 1];//重新申请内存 55 strcpy(st, s);//将字符串s复制到内存区st 56 return *this; 57 } 58 59 void main() 60 { 61 str s1("We"), s2("They"), s3(s1);//调用构造函数和复制构造函数 62 63 s1.print(); 64 s2.print(); 65 s3.print(); 66 67 s2 = s1 = s3;//调用赋值操作符 68 s3 = "Go home!";//调用字符串赋值操作符 69 s3 = s3;//调用赋值操作符但不进行赋值操作 70 71 s1.print(); 72 s2.print(); 73 s3.print(); 74 75 system("pause"); 76 };
例9.2
使用友元函数重载运算符“<<”和“>>”。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 class test 8 { 9 private: 10 int i; 11 float f; 12 char ch; 13 public: 14 test(int a = 0, float b = 0, char c = '\0') 15 { 16 i = a; 17 f = b; 18 ch = c; 19 } 20 friend ostream &operator<<(ostream &, test); 21 friend istream &operator>>(istream &, test &); 22 }; 23 24 ostream &operator<<(ostream & stream, test obj) 25 { 26 stream << obj.i << ","; 27 stream << obj.f << ","; 28 stream << obj.ch << endl; 29 return stream; 30 } 31 32 istream &operator>>(istream & t_stream, test &obj) 33 { 34 t_stream >> obj.i; 35 t_stream >> obj.f; 36 t_stream >> obj.ch; 37 return t_stream; 38 } 39 40 void main() 41 { 42 test A(45, 8.5, 'W'); 43 44 cout << A; 45 46 test B, C; 47 48 cout << "Input as i f ch:"; 49 50 cin >> B >> C; 51 52 cout << B << C; 53 54 system("pause"); 55 };
例9.3
使用类运算符重载“++”运算符。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 class number 8 { 9 int num; 10 public: 11 number(int i) 12 { 13 num = i; 14 } 15 int operator++();//前缀:++n 16 int operator++(int);//后缀:n++ 17 void print() 18 { 19 cout << "num=" << num << endl; 20 } 21 }; 22 23 int number::operator++() 24 { 25 num++; 26 return num; 27 } 28 29 int number::operator++(int)//不用给出形参名 30 { 31 int i = num; 32 num++; 33 return i; 34 } 35 36 void main() 37 { 38 number n(10); 39 40 int i = ++n;//i=11,n=11 41 cout << "i=" << i << endl;//输出i=11 42 n.print();//输出n=11 43 44 i = n++;////i=11,n=12 45 cout << "i=" << i << endl;//输出i=11 46 n.print();//输出n=12 47 48 system("pause"); 49 };
例9.4
使用友元运算符重载“++”运算符。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 class number 8 { 9 int num; 10 public: 11 number(int i) 12 { 13 num = i; 14 } 15 friend int operator++(number&);//前缀:++n 16 friend int operator++(number&, int);//后缀:n++ 17 void print() 18 { 19 cout << "num=" << num << endl; 20 } 21 }; 22 23 int operator++(number& a) 24 { 25 a.num++; 26 return a.num; 27 } 28 29 int operator++(number& a, int)//不用给出int类型的形参名 30 { 31 int i = a.num++; 32 return i; 33 } 34 35 void main() 36 { 37 number n(10); 38 39 int i = ++n;//i=11,n=11 40 cout << "i=" << i << endl;//输出i=11 41 n.print();//输出n=11 42 43 i = n++;////i=11,n=12 44 cout << "i=" << i << endl;//输出i=11 45 n.print();//输出n=12 46 47 system("pause"); 48 };
例9.5
使用对象作为友元函数参数来定义运算符“+”的例子。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 class complex 8 { 9 double real, imag; 10 public: 11 complex(double r = 0, double i = 0) 12 { 13 real = r; 14 imag = i; 15 } 16 friend complex operator+(complex, complex); 17 void show() 18 { 19 cout << real << "+" << imag << "i"; 20 } 21 }; 22 23 complex operator+(complex a, complex b) 24 { 25 double r = a.real + b.real; 26 double i = a.imag + b.imag; 27 return complex(r, i); 28 } 29 30 void main() 31 { 32 complex x(5, 3), y; 33 34 y = x + 7;//12+3i 35 y = 7 + y;//19+3i 36 y.show();//输出19+3i 37 38 system("pause"); 39 };
例9.6
设计类iArray,对其重载下标运算符[],并能在进行下标访问时检查下标是否越界。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 #include <iomanip> 5 6 using namespace std; 7 8 class iArray 9 { 10 int _size; 11 int *data; 12 public: 13 iArray(int); 14 int& operator[](int); 15 int size()const 16 { 17 return _size; 18 } 19 ~iArray() 20 { 21 delete[]data; 22 } 23 }; 24 25 iArray::iArray(int n)//构造函数中n>1 26 { 27 if (n < 1) 28 { 29 cout << "Error dimension description"; 30 exit(1); 31 } 32 _size = n; 33 data = new int[_size]; 34 } 35 36 int & iArray::operator[](int i)//合理范围0~_size-1 37 { 38 if (i < 0 || i > _size - 1)//检查越界 39 { 40 cout << "\nSubscript out of range"; 41 delete[]data;//释放数组所占内存空间 42 exit(1); 43 } 44 return data[i]; 45 } 46 47 void main() 48 { 49 iArray a(10); 50 cout << "数组元素个数=" << a.size() << endl; 51 52 for (int i = 0; i < a.size(); i++) 53 { 54 a[i] = 10 * (i + 1); 55 } 56 57 for (int i = 0; i < a.size(); i++) 58 { 59 cout << setw(5) << a[i]; 60 } 61 62 system("pause"); 63 };
例9.7
演示使用标志位的例子。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 const double PI = 3.141592; 8 9 void main() 10 { 11 int a = 15; 12 bool it = 1, not = 0; 13 14 cout << showpoint << 123.0 << " "//输出小数点 15 << noshowpoint << 123.0 << " ";//不输出小数点 16 cout << showbase;//演示输出数基 17 cout << a << " " << uppercase << hex << a << " " << nouppercase//演示大小写 18 << hex << a << " " << noshowbase << a << dec << a << endl; 19 20 cout << uppercase << scientific << PI << " " << nouppercase << PI << " " << fixed << PI << endl; 21 22 cout << cout.precision() << " " << PI << " ";//演示cout的成员函数 23 cout.precision(4); 24 cout << cout.precision() << " " << PI << endl; 25 26 cout.width(10); 27 cout << showpos << right << a << " " << noshowpos << PI << " ";//演示数值符号 28 cout << it << " " << not<< " " 29 << boolalpha << it << " " << " " << not<< " "//演示bool 30 << noboolalpha << " " << it << " " << not<< endl; 31 32 cout.width(10); 33 cout << left << PI << " " << 123 << " " << cout.width() << " "; 34 cout << 123 << " " << cout.width() << endl; 35 36 system("pause"); 37 };
例9.8
使用成员函数设置标志位的例子。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 5 using namespace std; 6 7 const double PI = 3.141592; 8 9 void main() 10 { 11 int a = 15; 12 13 cout.setf(ios_base::showpoint);//演示使用setf和unsetf 14 cout << 123.0 << " "; 15 cout.unsetf(ios_base::showpoint); 16 cout << 123.0 << endl; 17 18 cout.setf(ios_base::showbase); 19 cout.setf(ios_base::hex, ios_base::basefield); 20 cout << a << " " << uppercase << hex << a << " " << nouppercase//比较哪种方便 21 << hex << a << " " << noshowbase << a << dec << " " << a << endl; 22 23 float c = 23.56F, d = -101.22F; 24 cout.width(20); 25 cout.setf(ios_base::scientific | ios_base::right | ios_base::showpos, ios_base::floatfield); 26 cout << c << "\t" << d << "\t"; 27 cout.setf(ios_base::fixed | ios_base::showpos, ios_base::floatfield); 28 cout << c << "\t" << d << "\t"; 29 30 cout << cout.flags() << " " << 123.0 << " ";//演示输出flags 31 cout.flags(513);//演示设置flags 32 cout << 123.0 << endl; 33 34 cout.setf(ios_base::scientific);//演示省略方式 35 cout << 123.0 << endl; 36 37 cout.width(8);//设置填充字符数量(n-1) 38 cout << cout.fill('*') << 123 << endl;//演示填充 39 40 system("pause"); 41 };
例9.9
演示文件流的概念。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 #include <fstream>//输入输出文件流头文件 5 6 using namespace std; 7 8 void main() 9 { 10 int i; 11 12 char ch[15], *p = "abcdefg"; 13 14 ofstream myFILE;//建立输出流myFILE 15 myFILE.open("myText.txt");//建立输出流myFILE和myText.txt之间的关联 16 myFILE << p;//使用输出流myFILE将字符串流向文件 17 myFILE << "GoodBye!";//使用输出流myFILE直接将字符串流向文 18 myFILE.close();//关闭文件myText.txt 19 20 ifstream getText("myText.txt");//建立输入流getText及其和文件myText.txt的关联 21 22 for (i = 0; i < strlen(p) + 8; i++)//使用输入流getText每次从文件myText.txt读入1个字符 23 { 24 getText >> ch[i];//将每次读入的1个字符赋给数组的元素 25 } 26 ch[i] = '\0';//设置结束标志 27 28 getText.close();//关闭文件myText.txt 29 30 cout << ch;//使用cout流向屏幕 31 32 system("pause"); 33 };
例9.10
演示重载流运算符的例子。
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <iostream> 4 #include <fstream> 5 6 using namespace std; 7 8 struct list 9 { 10 double salary; 11 char name[20]; 12 friend ostream &operator<<(ostream &os, list &ob); 13 friend istream &operator>>(istream &is, list &ob); 14 }; 15 16 istream &operator>>(istream &is, list &ob)//重载”>>“运算符 17 { 18 is >> ob.name; 19 is >> ob.salary; 20 return is; 21 } 22 23 ostream &operator<<(ostream &os, list &ob)//重载”<<“运算符 24 { 25 os << ob.name << ' '; 26 os << ob.salary << ' '; 27 return os; 28 } 29 30 void main() 31 { 32 int i; 33 34 list worker1[2] = { {1256,"LiMing"},{3467,"ZhangHong"} }, worker2[2]; 35 ofstream out("pay.txt", ios::binary); 36 37 if (!out) 38 { 39 cout << "没有正确建立文件,结束程序运行!" << endl; 40 return; 41 } 42 43 for (int i = 0; i < 2; i++) 44 { 45 out << worker1[i];//将worker1[i]作为整体对待 46 } 47 out.close(); 48 49 ifstream in("pay.txt", ios::binary); 50 51 if (!in) 52 { 53 cout << "没有正确建立文件,结束程序运行!" << endl; 54 return; 55 } 56 57 for (i = 0; i < 2; i++) 58 { 59 in >> worker2[i];//将worker2[i]整体读入 60 cout << worker2[i] << endl;//将worker2[i]整体输出 61 } 62 63 in.close(); 64 65 system("pause"); 66 };
文件存取综合实例
头文件student.h
源文件student.cpp
头文件student.h
1 #if ! defined(STUDENT_H) 2 #define STUDENT_H 3 #include<iostream> 4 #include<string> 5 #include<iomanip> 6 #include<vector> 7 #include<fstream> 8 using namespace std; 9 10 class student 11 { 12 string number; 13 double score; 14 public: 15 void SetNum(string s) 16 { 17 number = s; 18 } 19 void SetScore(double s) 20 { 21 score = s; 22 } 23 string GetNum() 24 { 25 return number; 26 } 27 double GetScore() 28 { 29 return score; 30 } 31 void set(vector<student>&);//输入信息并存入向量和文件中 32 void display(vector<student>&);//显示向量信息 33 void read();//读入文件内容 34 }; 35 #endif
源文件student.cpp
1 #include"student.h" 2 //******************************* 3 //* 成员函数:display * 4 //* 参 数:向量对象的引用 * 5 //* 返 回 值:无 * 6 //* 功 能:输出向量信息 * 7 //******************************* 8 void student::display(vector<student>&c) 9 { 10 cout << "学号" << setw(20) << "成绩" << endl; 11 for (int i = 0; i < c.size(); i++)//循环显示向量对象的信息 12 { 13 cout << c[i].GetNum() << setw(12) << c[i].GetScore() << endl; 14 } 15 } 16 //******************************* 17 //* 成员函数:set * 18 //* 参 数:向量对象的引用 * 19 //* 返 回 值:无 * 20 //* 功 能:为向量赋值并将 * 21 // 向量内容存入文件 * 22 //******************************* 23 void student::set(vector<student>&c) 24 { 25 student a;//定义对象a作为数据临时存储 26 string s;//定义临时存储输入学号的对象 27 double b;//定义临时存储输入成绩的对象 28 while (1)//输入数据 29 { 30 cout << "学号:"; 31 cin >> s;//取得学号或者结束标志 32 if (s == "0")//结束输入并将结果存入文件 33 { 34 ofstream wst("stud.txt");//建立文件stud.txt 35 if (!wst)//文件出错处理 36 { 37 cout << "没有正确建立文件!" << endl; 38 return;//文件出错结束程序运行 39 } 40 for (int i = 0; i < c.size(); i++)//将向量内存存入文件 41 { 42 wst << c[i].number << " " << c[i].score << " "; 43 } 44 wst.close();//关闭文件 45 cout << "一共写入" << c.size() << "个学生的信息。\n"; 46 return;//正确存入文件后,结束程序运行 47 } 48 a.SetNum(s);//存入学号 49 cout << "成绩:"; 50 cin >> b; 51 a.SetScore(b);//取得成绩 52 c.push_back(a);//将a的内容追加到向量c的尾部 53 } 54 } 55 //******************************* 56 //* 成员函数:read * 57 //* 参 数:无 * 58 //* 返 回 值:无 * 59 //* 功 能:显示文件内容 * 60 //******************************* 61 void student::read() 62 { 63 string number; 64 double scroe; 65 ifstream rst("stud.txt");//打开文件stud.txt 66 if (!rst)//文件出错处理 67 { 68 cout << "文件打不开\n" << endl; 69 return;//文件出错,结束程序运行 70 } 71 cout << "学号" << setw(20) << "成绩" << endl; 72 while (1)//每次读取一条完整信息 73 { 74 rst >> number >> score; 75 if (rst.eof())//判别是否读完文件内容 76 { 77 rst.close();//读完则关闭文件 78 return;//结束程序运行 79 } 80 cout << number << setw(12) << score << endl;//显示一条信息 81 } 82 } 83 84 void main() 85 { 86 vector<student>st;//向量st的数据类型为double 87 student stud; 88 stud.set(st);//stud调用成员函数set接受输入并建立文件 89 cout << "显示向量数组信息如下:\n"; 90 stud.display(st);//显示向量内容 91 cout << "存入文件内的信息如下:" << endl; 92 stud.read();//stud调用read读出文件内容 93 94 system("pause"); 95 }