04737_C++程序设计_第9章_运算符重载及流类库

例9.1

完整实现str类的例子。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>
#include <string> using namespace std; class str
{
private:
char *st;
public:
str(char *s);//使用字符指针的构造函数
str(str& s);//使用对象引用的构造函数
str& operator=(str& a);//重载使用对象引用的赋值运算符
str& operator=(char *s);//重载使用指针的赋值运算符
void print()
{
cout << st << endl;//输出字符串
}
~str()
{
delete st;
}
}; str::str(char *s)
{
st = new char[strlen(s) + ];//为st申请内存
strcpy(st, s);//将字符串s复制到内存区st
} str::str(str& a)
{
st = new char[strlen(a.st) + ];//为st申请内存
strcpy(st, a.st);//将对象a的字符串复制到内存区st
} str& str::operator=(str& a)
{
if (this == &a)//防止a=a这样的赋值
{
return *this;//a=a,退出
}
delete st;//不是自身,先释放内存空间
st = new char[strlen(a.st) + ];//重新申请内测
strcpy(st, a.st);//将对象a的字符串复制到申请的内存区
return *this;//返回this指针指向的对象
} str& str::operator=(char *s)
{
delete st;//是字符串直接赋值,先释放内存空间
st = new char[strlen(s) + ];//重新申请内存
strcpy(st, s);//将字符串s复制到内存区st
return *this;
} void main()
{
str s1("We"), s2("They"), s3(s1);//调用构造函数和复制构造函数 s1.print();
s2.print();
s3.print(); s2 = s1 = s3;//调用赋值操作符
s3 = "Go home!";//调用字符串赋值操作符
s3 = s3;//调用赋值操作符但不进行赋值操作 s1.print();
s2.print();
s3.print(); system("pause");
};

例9.2

使用友元函数重载运算符“<<”和“>>”。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 class test
{
private:
int i;
float f;
char ch;
public:
test(int a = , float b = , char c = '\0')
{
i = a;
f = b;
ch = c;
}
friend ostream &operator<<(ostream &, test);
friend istream &operator>>(istream &, test &);
}; ostream &operator<<(ostream & stream, test obj)
{
stream << obj.i << ",";
stream << obj.f << ",";
stream << obj.ch << endl;
return stream;
} istream &operator>>(istream & t_stream, test &obj)
{
t_stream >> obj.i;
t_stream >> obj.f;
t_stream >> obj.ch;
return t_stream;
} void main()
{
test A(, 8.5, 'W'); cout << A; test B, C; cout << "Input as i f ch:"; cin >> B >> C; cout << B << C; system("pause");
};

例9.3

使用类运算符重载“++”运算符。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 class number
{
int num;
public:
number(int i)
{
num = i;
}
int operator++();//前缀:++n
int operator++(int);//后缀:n++
void print()
{
cout << "num=" << num << endl;
}
}; int number::operator++()
{
num++;
return num;
} int number::operator++(int)//不用给出形参名
{
int i = num;
num++;
return i;
} void main()
{
number n(); int i = ++n;//i=11,n=11
cout << "i=" << i << endl;//输出i=11
n.print();//输出n=11 i = n++;////i=11,n=12
cout << "i=" << i << endl;//输出i=11
n.print();//输出n=12 system("pause");
};

例9.4

使用友元运算符重载“++”运算符。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 class number
{
int num;
public:
number(int i)
{
num = i;
}
friend int operator++(number&);//前缀:++n
friend int operator++(number&, int);//后缀:n++
void print()
{
cout << "num=" << num << endl;
}
}; int operator++(number& a)
{
a.num++;
return a.num;
} int operator++(number& a, int)//不用给出int类型的形参名
{
int i = a.num++;
return i;
} void main()
{
number n(); int i = ++n;//i=11,n=11
cout << "i=" << i << endl;//输出i=11
n.print();//输出n=11 i = n++;////i=11,n=12
cout << "i=" << i << endl;//输出i=11
n.print();//输出n=12 system("pause");
};

例9.5

使用对象作为友元函数参数来定义运算符“+”的例子。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 class complex
{
double real, imag;
public:
complex(double r = , double i = )
{
real = r;
imag = i;
}
friend complex operator+(complex, complex);
void show()
{
cout << real << "+" << imag << "i";
}
}; complex operator+(complex a, complex b)
{
double r = a.real + b.real;
double i = a.imag + b.imag;
return complex(r, i);
} void main()
{
complex x(, ), y; y = x + ;//12+3i
y = + y;//19+3i
y.show();//输出19+3i system("pause");
};

例9.6

设计类iArray,对其重载下标运算符[],并能在进行下标访问时检查下标是否越界。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>
#include <iomanip> using namespace std; class iArray
{
int _size;
int *data;
public:
iArray(int);
int& operator[](int);
int size()const
{
return _size;
}
~iArray()
{
delete[]data;
}
}; iArray::iArray(int n)//构造函数中n>1
{
if (n < )
{
cout << "Error dimension description";
exit();
}
_size = n;
data = new int[_size];
} int & iArray::operator[](int i)//合理范围0~_size-1
{
if (i < || i > _size - )//检查越界
{
cout << "\nSubscript out of range";
delete[]data;//释放数组所占内存空间
exit();
}
return data[i];
} void main()
{
iArray a();
cout << "数组元素个数=" << a.size() << endl; for (int i = ; i < a.size(); i++)
{
a[i] = * (i + );
} for (int i = ; i < a.size(); i++)
{
cout << setw() << a[i];
} system("pause");
};

例9.7

演示使用标志位的例子。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 const double PI = 3.141592;

 void main()
{
int a = ;
bool it = , not = ; cout << showpoint << 123.0 << " "//输出小数点
<< noshowpoint << 123.0 << " ";//不输出小数点
cout << showbase;//演示输出数基
cout << a << " " << uppercase << hex << a << " " << nouppercase//演示大小写
<< hex << a << " " << noshowbase << a << dec << a << endl; cout << uppercase << scientific << PI << " " << nouppercase << PI << " " << fixed << PI << endl; cout << cout.precision() << " " << PI << " ";//演示cout的成员函数
cout.precision();
cout << cout.precision() << " " << PI << endl; cout.width();
cout << showpos << right << a << " " << noshowpos << PI << " ";//演示数值符号
cout << it << " " << not<< " "
<< boolalpha << it << " " << " " << not<< " "//演示bool
<< noboolalpha << " " << it << " " << not<< endl; cout.width();
cout << left << PI << " " << << " " << cout.width() << " ";
cout << << " " << cout.width() << endl; system("pause");
};

例9.8

使用成员函数设置标志位的例子。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>

 using namespace std;

 const double PI = 3.141592;

 void main()
{
int a = ; cout.setf(ios_base::showpoint);//演示使用setf和unsetf
cout << 123.0 << " ";
cout.unsetf(ios_base::showpoint);
cout << 123.0 << endl; cout.setf(ios_base::showbase);
cout.setf(ios_base::hex, ios_base::basefield);
cout << a << " " << uppercase << hex << a << " " << nouppercase//比较哪种方便
<< hex << a << " " << noshowbase << a << dec << " " << a << endl; float c = 23.56F, d = -101.22F;
cout.width();
cout.setf(ios_base::scientific | ios_base::right | ios_base::showpos, ios_base::floatfield);
cout << c << "\t" << d << "\t";
cout.setf(ios_base::fixed | ios_base::showpos, ios_base::floatfield);
cout << c << "\t" << d << "\t"; cout << cout.flags() << " " << 123.0 << " ";//演示输出flags
cout.flags();//演示设置flags
cout << 123.0 << endl; cout.setf(ios_base::scientific);//演示省略方式
cout << 123.0 << endl; cout.width();//设置填充字符数量(n-1)
cout << cout.fill('*') << << endl;//演示填充 system("pause");
};

例9.9

演示文件流的概念。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>
#include <fstream>//输入输出文件流头文件 using namespace std; void main()
{
int i; char ch[], *p = "abcdefg"; ofstream myFILE;//建立输出流myFILE
myFILE.open("myText.txt");//建立输出流myFILE和myText.txt之间的关联
myFILE << p;//使用输出流myFILE将字符串流向文件
myFILE << "GoodBye!";//使用输出流myFILE直接将字符串流向文
myFILE.close();//关闭文件myText.txt ifstream getText("myText.txt");//建立输入流getText及其和文件myText.txt的关联 for (i = ; i < strlen(p) + ; i++)//使用输入流getText每次从文件myText.txt读入1个字符
{
getText >> ch[i];//将每次读入的1个字符赋给数组的元素
}
ch[i] = '\0';//设置结束标志 getText.close();//关闭文件myText.txt cout << ch;//使用cout流向屏幕 system("pause");
};

例9.10

演示重载流运算符的例子。

 #define _CRT_SECURE_NO_WARNINGS

 #include <iostream>
#include <fstream> using namespace std; struct list
{
double salary;
char name[];
friend ostream &operator<<(ostream &os, list &ob);
friend istream &operator>>(istream &is, list &ob);
}; istream &operator>>(istream &is, list &ob)//重载”>>“运算符
{
is >> ob.name;
is >> ob.salary;
return is;
} ostream &operator<<(ostream &os, list &ob)//重载”<<“运算符
{
os << ob.name << ' ';
os << ob.salary << ' ';
return os;
} void main()
{
int i; list worker1[] = { {,"LiMing"},{,"ZhangHong"} }, worker2[];
ofstream out("pay.txt", ios::binary); if (!out)
{
cout << "没有正确建立文件,结束程序运行!" << endl;
return;
} for (int i = ; i < ; i++)
{
out << worker1[i];//将worker1[i]作为整体对待
}
out.close(); ifstream in("pay.txt", ios::binary); if (!in)
{
cout << "没有正确建立文件,结束程序运行!" << endl;
return;
} for (i = ; i < ; i++)
{
in >> worker2[i];//将worker2[i]整体读入
cout << worker2[i] << endl;//将worker2[i]整体输出
} in.close(); system("pause");
};

文件存取综合实例

头文件student.h

源文件student.cpp

头文件student.h

 #if ! defined(STUDENT_H)
#define STUDENT_H
#include<iostream>
#include<string>
#include<iomanip>
#include<vector>
#include<fstream>
using namespace std; class student
{
string number;
double score;
public:
void SetNum(string s)
{
number = s;
}
void SetScore(double s)
{
score = s;
}
string GetNum()
{
return number;
}
double GetScore()
{
return score;
}
void set(vector<student>&);//输入信息并存入向量和文件中
void display(vector<student>&);//显示向量信息
void read();//读入文件内容
};
#endif

源文件student.cpp

 #include"student.h"
//*******************************
//* 成员函数:display *
//* 参 数:向量对象的引用 *
//* 返 回 值:无 *
//* 功 能:输出向量信息 *
//*******************************
void student::display(vector<student>&c)
{
cout << "学号" << setw() << "成绩" << endl;
for (int i = ; i < c.size(); i++)//循环显示向量对象的信息
{
cout << c[i].GetNum() << setw() << c[i].GetScore() << endl;
}
}
//*******************************
//* 成员函数:set *
//* 参 数:向量对象的引用 *
//* 返 回 值:无 *
//* 功 能:为向量赋值并将 *
// 向量内容存入文件 *
//*******************************
void student::set(vector<student>&c)
{
student a;//定义对象a作为数据临时存储
string s;//定义临时存储输入学号的对象
double b;//定义临时存储输入成绩的对象
while ()//输入数据
{
cout << "学号:";
cin >> s;//取得学号或者结束标志
if (s == "")//结束输入并将结果存入文件
{
ofstream wst("stud.txt");//建立文件stud.txt
if (!wst)//文件出错处理
{
cout << "没有正确建立文件!" << endl;
return;//文件出错结束程序运行
}
for (int i = ; i < c.size(); i++)//将向量内存存入文件
{
wst << c[i].number << " " << c[i].score << " ";
}
wst.close();//关闭文件
cout << "一共写入" << c.size() << "个学生的信息。\n";
return;//正确存入文件后,结束程序运行
}
a.SetNum(s);//存入学号
cout << "成绩:";
cin >> b;
a.SetScore(b);//取得成绩
c.push_back(a);//将a的内容追加到向量c的尾部
}
}
//*******************************
//* 成员函数:read *
//* 参 数:无 *
//* 返 回 值:无 *
//* 功 能:显示文件内容 *
//*******************************
void student::read()
{
string number;
double scroe;
ifstream rst("stud.txt");//打开文件stud.txt
if (!rst)//文件出错处理
{
cout << "文件打不开\n" << endl;
return;//文件出错,结束程序运行
}
cout << "学号" << setw() << "成绩" << endl;
while ()//每次读取一条完整信息
{
rst >> number >> score;
if (rst.eof())//判别是否读完文件内容
{
rst.close();//读完则关闭文件
return;//结束程序运行
}
cout << number << setw() << score << endl;//显示一条信息
}
} void main()
{
vector<student>st;//向量st的数据类型为double
student stud;
stud.set(st);//stud调用成员函数set接受输入并建立文件
cout << "显示向量数组信息如下:\n";
stud.display(st);//显示向量内容
cout << "存入文件内的信息如下:" << endl;
stud.read();//stud调用read读出文件内容 system("pause");
}
上一篇:acdream 1685 多民族王国(DFS,并查集)


下一篇:21天学通C++学习笔记(二):C++程序的组成部分