实验2 类和对象(2)
实验结论
实验任务4

1 #pragma once 2 #include<iostream> 3 #include<cmath> 4 using namespace std; 5 class Complex{ 6 public: 7 Complex(double r=0.0,double i=0.0); 8 Complex(const Complex &obj): real{obj.real}, imag{obj.imag} {} 9 double get_real() const; 10 double get_imag() const; 11 void show() const; 12 void add(Complex c); 13 friend Complex add(Complex c1, Complex c2); 14 friend bool is_equal(Complex c1, Complex c2); 15 friend double abs(Complex c); 16 17 private: 18 double real; 19 double imag; 20 21 }; 22 23 Complex::Complex(double r, double i):real{r},imag{i} {} 24 double Complex::get_real() const {return real;} 25 double Complex::get_imag() const {return imag;} 26 void Complex::show() const { 27 cout << Complex::get_real(); 28 if(get_imag() > 0) cout << " + "<< Complex::get_imag() << "i" <<endl; 29 else if(get_imag() < 0) cout << " - "<< Complex::get_imag()*-1 << "i" <<endl; 30 else cout << endl; 31 } 32 void Complex::add(Complex c) { 33 real += c.get_real(); 34 imag += c.get_imag(); 35 } 36 Complex add(Complex c1, Complex c2){ 37 return Complex(c1.real + c2.real, c1.imag + c2.imag); 38 } 39 bool is_equal(Complex c1, Complex c2){ 40 if(c1.real == c2.real && c1.imag == c2.imag) return true; 41 else return false; 42 } 43 double abs(Complex c){ 44 return sqrt(c.real*c.real+c.imag*c.imag); 45 }
实验任务5

1 #include<iostream> 2 #include<string> 3 #include<iomanip> 4 using namespace std; 5 class User{ 6 public: 7 User(string name0, string password0 = "111111", string email0 = " "); 8 void set_email(); 9 void change_passwd(); 10 void print_info() const; 11 void static print_n(); 12 private: 13 string name,password,email; 14 static int count; 15 16 }; 17 18 int User::count = 0; 19 User::User(string name0, string password0, string email0): 20 name{name0},password{password0},email{email0} { 21 count++;} 22 23 void User::set_email(){ 24 cout << "Enter email address: "; 25 cin >> email; 26 cout << "email is set successfully..." << endl; 27 28 } 29 30 void User::change_passwd(){ 31 int times=0; 32 cout << "Enter old password: "; 33 while(times++ < 3){ 34 string s1; 35 cin >> s1; 36 if(s1 == password ){ 37 cout << "Enter new passwd: "; 38 cin >> password; 39 cout << "new passwd is set successfully..." << endl; 40 break; 41 } 42 else if(times < 3) cout << "password input error. Please re-enter again: "; 43 } 44 if(times >= 3) cout << "password input error. Please try after a while."<<endl; 45 } 46 47 void User::print_info() const{ 48 string s1(password.length(), '*'); 49 cout << left << setw(8) << "name:" << name << endl; 50 cout << left << setw(8) << "passwd:" << s1 << endl; 51 cout << left << setw(8) << "email:" << email << endl; 52 } 53 void User::print_n() {cout <<"there are "<< count << " users" <<endl;}
实验总结
1.函数调用静态变量时需声明为静态函数