1.编写重载函数add(),实现对int型,double型,Complex型数据的加法。在main()函数中定义不同类型 数据,调用测试。
#include <iostream> using namespace std; struct complex{ double real; double imaginary; }; int add(int a,int b) { return a+b; } double add(double x,double y) { return x+y; } complex add(complex m,complex n) { complex z; z.real=m.real+n.real; z.imaginary=m.imaginary+n.imaginary; return z; } int main() { int a,b; cout<<"输入两个整数:"; cin>>a>>b; cout<<"两数之和:"<<add(a,b)<<endl; double x,y; cout<<"输入两个双精度型的数:"; cin>>x>>y; cout<<"两数之和:"<<add(x,y)<<endl; complex m,n,z; cout<<"输入两个复数:"; cin>>m.real>>m.imaginary>>n.real>>n.imaginary; z=add(m,n); cout<<z.real<<"+"<<z.imaginary<<"i"<<endl; return 0; }
2.编写实现快速排序函数模板,并在main()函数中,定义不同类型数据,调用测试。
#ifndef Quicksort #define Quicksort template <class T> void QSort(T a[], int low, int high) { int i(low),j(high-1),k(0); T b, c; b = s[(low+high)/2]; if (i < j) { while (i < j) { while (i < j&&b < a[j]) j--; while (i < j&&b > a[i]) i++; if (i >= j) k = j; else { c = a[i]; a[i] = a[j]; a[j] = c; } } QSort(a, low, k); QSort(a, k + 1, high); } } #endif #include <iostream> #include "QSort.h" #include <iomanip> using namespace std; int main() { int i; int a[5]={12,29,19,119,90}; double b[5]={2.3,7.9,12.0,6.8,12.9}; QSort(a,0,5); for(i=0;i<5;i++) cout<<a[i]<<endl; QSort(b,0,5); for(i=0;i<5;i++) cout<<b[i]<<endl; return 0; }
3.设计并实现一个用户类User,并在主函数中使用和测试这个类。具体要求如下: 每一个用户有用户名(name), 密码(passwd),联系邮箱(email)三个属性。 支持设置用户信息setInfo()。允许设置信息时密码默认为6个1,联系邮箱默认为空串。 支持打印用户信息printInfo()。打印用户名、密码、联系邮箱。其中,密码以6个*方式显示。 支持修改密码changePasswd(),。在修改密码前,要求先输入旧密码,验证无误后,才允许修改。 如果输入旧密码时,连续三次输入错误,则提示用户稍后再试,暂时退出修改密码程序。 在main()函数中创建User类实例,测试User类的各项操作(设置用户信息,修改密码,打印用户信息)
#include <iostream> #include <string> using namespace std; class User { public: User(string name1,string passwd1,string email1); User() { name=" "; passwd="111111"; email=" "; } void setInfo(string name1="",string passwd1="111111",string email1=""); void changePasswd(); void printInfo(); private: string name; string passwd; string email; }; void User::setInfo(string name1,string passwd1,string email1) { name=name1; passwd=passwd1; email=email1; } void User::changePasswd() { string oldpasswd; int i=1; cout<<"input oldpasswd:"; cin>>oldpasswd; while(oldpasswd!=passwd&&i<3) { cout<<"It‘s wrong,try again."; cin>>oldpasswd; i++; } if(oldpasswd!=passwd&&i==3) cout<<"Please try it later."; if(oldpasswd==passwd) { cout<<"change your passwd:"; cin>>passwd; } } void User::printInfo() { cout<<"name:"<<name<<endl; cout<<"passwd:******"<<endl; cout<<"email:"<<email<<endl; } int main() { cout<<"testing 1......"<<endl; User user1; user1.setInfo("Leonard"); user1.printInfo(); user1.changePasswd(); user1.printInfo(); cout<<endl<<"testing 2......"<<endl<<endl; User user2; user2.setInfo("Jonny","92197","xyz@hotmail.com"); user2.printInfo(); return 0; }
实验总结与体会:
对于快速排序函数模板的掌握并不好,不知道如何将程序加入项目中,一直提示错误并且出不了结果。所以借鉴了别人的程序。
对于重载函数,整数类型和双精度型根据书上还可以编写,对于结构体还是不会编写,还是自己在实验前没有复习结构体的内容,实验准备不够充分,需要反思。
原文:https://www.cnblogs.com/mzy-1229/p/10590910.html