实验一 类与对象
实验结论:
实验任务三:
Complex.hpp
#include<iostream> #include<math.h> using namespace std; class Complex { public: Complex():real(0),imag(0){} Complex(float x) :real(x),imag(0){} Complex(float x,float y):real(x),imag(y){} float get_real()const{return real;} float get_imag()const{return imag;} void show()const{ if(imag==0)cout<<real<<endl; if(imag>0)cout<<real<<"+"<<imag<<"I"<<endl; if(imag<0) cout<<real<<imag<<"i"<<endl;} void add(Complex p){real+=p.real;imag+=p.imag;} friend Complex add(Complex a,Complex b){ Complex c; c.real=a.real+b.real; c.imag=a.imag+b.imag; return c; } friend bool is_equal(Complex a,Complex b){if(a.real==b.real&&a.imag==b.imag) return true; if(a.real!=b.real||a.imag!=b.imag) return false;} friend float abs(Complex &a){ float x; x=sqrt(a.real*a.real+a.imag*a.imag); return x; } private: float real; float imag; };
task3.cpp
#include<math.h> #include <iostream> #include"Complex.hpp" using namespace std; int main() { using namespace std; Complex c1(3, -4); const Complex c2(4.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; }
运行截图:

更换数据后的截图:

实验任务四:
User.hpp:
#include<iostream> #include<string> using namespace std; class User{ public: User(string a,string b="111111",string c=" "):name(a){passwd=b;email=c;n++;} void set_email(){char a; cout<<"Enter email address:"; cin>>a; email=a; cout<<email<<endl; cout<<"email is set successfully..."<<endl; } void change_passwd(){ string a; int n=3; cout<<"Enter old password:"; while(1){ cin>>a; if(a!=passwd){cout<<"password input error.Please re-enter again:";n--;} if(n==0){cout<<"password input error.Please try after a while."<<endl;break;} if(a==passwd){ cout<<"Enter new passward:"; cin>>a; passwd=a; break;} } } void print_info() { cout<<"name:"<<name<<endl; cout<<"passwd:"<<"******"<<endl; cout<<"email:"<<email<<endl; } static void print_n() { cout<<"there are "<<n<<" users"<<endl; } private: static int n; string name; string email; string passwd; }; int User::n=0;
task4.cpp:
#include"User.hpp" #include<string> #include <iostream> using namespace std; int main() { using namespace std; cout << "testing 1......" << endl; User user1("Jonny", "92197", "xyz@hotmail.com"); user1.print_info(); cout << endl << "testing 2......" << endl << endl; User user2("Leonard"); user2.change_passwd(); user2.set_email(); user2.print_info(); User::print_n(); }
运行截图:

输入密码没有错误的运行截图:

更换数据后的运行截图:


浙公网安备 33010602011771号