实验一 类与对象
#include<iostream> #include<cmath> using namespace std; class Complex{ private: double real, imag; public: Complex(); Complex(double r = 0, double i = 0); Complex(double r); Complex(const Complex &c); double get_real() const double get_imag() const void show() const; void add(const Complex &c); friend Complex add(const Complex &c1, const Complex &c2); friend bool is_equal(const Complex &c1, const Complex &c2); friend double abs(const Complex &c); }; 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"; } } } } void Complex::add(const Complex &c){ real += c.real; imag += c.imag; } Complex add(const Complex &c1, const Complex &c2){ Complex c3; c3.real = c1.real + c2.real; c3.imag = c1.imag + c2.imag; return c; } bool is_equal(const Complex &c1, const Complex &c2){ if(c1.real==c2.real && c1.imag==c2.imag) return true; return false; } double abs(const Complex &c){ double s = sqrt(c.real * c.real + c.imag * c.imag); return s; }
task 3:
#include "Complex.hpp" #include <iostream> int main() { using namespace std; Complex c1(8, -9); const Complex c2(6.5); Complex c3(c1); cout << "c1 = "; c1.show(); cout << endl; cout << "c2 = "; c2.show(); cout << endl; cout << "c2.imag = " << c2.get_imag() << endl; cout << "c3 = "; c3.show(); cout << endl; cout << "abs(c1) = "; cout << abs(c1) << endl; cout << boolalpha; cout << "c1 == c3 : " << is_equal(c1, c3) << endl; cout << "c1 == c2 : " << is_equal(c1, c2) << endl; Complex c4; c4 = add(c1, c2); cout << "c4 = c1 + c2 = "; c4.show(); cout << endl; c1.add(c2); cout << "c1 += c2, " << "c1 = "; c1.show(); cout << endl; }
输出结果:

实验任务 4:
User.hpp:
#include<iostream> #include<string> using namespace std; class User { private: string name,password,email; static int n; public: User(string n1); User(string n1,string p1,string e1); void set_email(); void change_passwd(); void print_info(); static void print_n(); }; int User::n=0; User::User(string n1) { n++; name=n1; password="111111"; email=""; } User::User(string n1,string p1,string e1) { n++; name=n1; password=p1; email=e1; } void User::set_email() { string ad; cout<<"Enter email address:"; cin>>ad; email=ad; cout<<"email is set successfully"<<endl; } void User::change_passwd() { string 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; }

浙公网安备 33010602011771号