task 3 Complex.hpp 代码如下:
#include<iostream> #include<math.h> using namespace std; class Complex{ public: Complex(); Complex(double real1,double imag1); Complex(double real1); Complex(const Complex &r); //复制构造函数 double get_real() const; //返回函数实部 double get_imag() const; //返回函数虚部 void show() const; //输出结果 void add(Complex &m); //一个复数加上本身 friend Complex add(const Complex &c1,const Complex &c2); //实现两个复数相加 friend bool is_equal(const Complex &c1,const Complex &c2); //bool型判断两个复数是否相同 friend double abs(const Complex &x1); //计算复数的取模运算 private: double real,imag; }; Complex::Complex():real(0),imag(0){ } Complex::Complex(double real1) { real=real1; imag=0; // cout<<real<<endl; } Complex::Complex(double real1,double imag1) { real=real1; imag=imag1; } Complex::Complex(const Complex &r) { real=r.real; imag=r.imag; } double Complex::get_real() const { //cout<<real<<endl; return real; } double Complex::get_imag() const { return imag; } void Complex::add(Complex &m) { real=real+m.real; imag=imag+m.imag; } void Complex::show() const { double n1,n2; n1=get_real(); //cout<<n1<<endl; n2=get_imag(); if(n1==0&&n2==0) { cout<<n1; } else { if(n1==0) { cout<<n2<<"i"; } else { if(n2==0) { cout<<n1; } else { if(n2>0) cout<<n1<<"+"<<n2<<"i"; else cout<<n1<<n2<<"i"; } } } } Complex add(const Complex &c1,const Complex &c2) { Complex c3; c3.real=c1.real+c2.real; c3.imag=c1.imag+c2.imag; return c3; } double abs(const Complex &x1) { double x; x=sqrt(x1.real*x1.real+x1.imag*x1.imag); return x; } bool is_equal(const Complex &c1,const Complex &c2) { if(c1.real==c2.real&&c1.imag==c2.imag) return true; else return false; }
更换数据后运行结果如下:
task4 User.hpp 代码如下:
#include<iostream> #include<string> using namespace std; class User{ public: User(string name1); User(string name1,string password1,string email1); void set_email(); //设置email void change_passwd(); //改密码 void print_info(); //输出结果 static void print_n(); private: string name,password,email; static int n; //直接操作类的成员需要用静态变量 }; int User::n=0; //静态成员只能类外初始化 User::User(string name1) { name=name1; password="111111"; email=""; n++; } User::User(string name1,string password1,string email1) { name=name1; password=password1; email=email1; n++; } 111 void User::set_email() { string t; cout<<"Enter email address:"; cin>>t; email=t; cout<<"email is set successfully···"<<endl; } void User::change_passwd() { string t0,t1; //t0作原密码,t1作新密码 cout<<"Enter old password:"; for(int i=1;i<=3;i++) { cin>>t0; if(t0==password) { cout<<"Enter new password:"; cin>>t1; password=t1; break; } else if(i<=2){ cout<<"password input error. Please re-enter again:"; } else cout<<"password input error. Please try after a while."<<endl; //三次错误则无法再输入 } } void User::print_info() { cout<<"name:"<<name<<endl; cout<<"passwd:"<<"******"<<endl; cout<<"email:"<<email<<endl; } void User::print_n() { if(n==1) cout<<"there are "<<n<<" user."<<endl; else cout<<"there are "<<n<<" users."<<endl; }
更换数据后运行结果如下: