题目一
使用函数模板实现swap(&x,&y)交换两个实参变量a和b的指。
#include"iostream"
using namespace std;
template<class T>
T Swap(T&x , T&y){
T temp=x;
x=y;
y=temp;
}
int main(){
int m=3,n=2;
cout<<"原本:"<<endl;
cout<<"m="<<m<<" "<<"n="<<n<<endl;
Swap(m,n);
cout<<"使用模版:"<<endl;
cout<<"m="<<m<<" "<<"n="<<n<<endl;
return 0;
}
题目二
编写一个复数类模板Complex,其数据成员real和image的类型未知,定义相同的成员函数,实现构造、输出、加、减等功能。在主函数中定义模板类对象,分别以int和double实例化类型参数,实现复数中的相关操作。
#include"iostream"
using namespace std;
template<class T>
class Complex{
private:
T real;
T image;
public:
Complex(T real=0,T image=0):real(real),image(image){}//初始化列表
void show(){//输出函数
cout<<real<<"+"<<image<<"i"<<endl;
}
Complex operator+(Complex c){//加法
return Complex(real+c.real,image+c.image);
}
Complex operator-(Complex c){//减法
return Complex(real-c.real,image-c.image);
}
};
int main(){
cout<<"使用int实例化参数所得值:";
Complex<int> c1(1,2);
Complex<int> c2(3,4);
Complex<int> c3=c2-c1;
c3.show();
cout<<endl;
cout<<"使用double实例化参数所得值:";
Complex<double> c4(2,2);
Complex<double> c5(3,4);
Complex<double> c6=c5-c4;
c6.show();
return 0;
}
题目三
定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上
#include"iostream"
#include"string"
#include"fstream"
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(string name="无",int age=1):name(name),age(age){}
void show(){
cout<<name<<","<<age<<endl;
}
friend istream& operator>>(istream& in,Person& o);
friend ostream& operator<<(ostream& out,const Person& o);
};
istream& operator>>(istream& in,Person& o){
in>>o.name>>o.age;
return in;
}
ostream& operator<<(ostream& out, const Person& o) {
out<<o.name<<" "<<o.age;
return out;
}
void createFile(string filename,const Person o[],const int len){
ofstream out(filename.c_str(),ios::app);
if(!out){
cout<<"create file fail\n"<<endl;
return;
}
for(int i=0;i<len;i++){
out<<o[i];
if(i<len-1)
out<<"\n";
}
out.close();
}
void readFile(string filename){
ifstream in(filename.c_str());
if(!in){
cout<<"open file fail\n"<< endl;
return;
}
while(!in.eof()){
Person p;
in>>p;
p.show();
}
in.close();
}
int main(){
string filename="D:\\person.txt";
Person o[5]={Person("小明",18),Person("小红",17),Person("小军",20)
,Person("老强",40),Person("老登",50)};
createFile(filename,o,5);
readFile(filename);
return 0;
}