实验二 类与对象(2)
4
#pragma once #include<iostream> #include<iomanip> #include<complex> using namespace std; class Complex { public: double re, im, ab; Complex(); Complex(double x); Complex(double x, double y); Complex(const Complex &obj); double get_real() const {return re;}; double get_imag() const {return im;}; void show() const; void add(Complex obj); friend Complex add(Complex c1,Complex c2); friend bool is_equal(Complex c1, Complex c2); friend double abs(Complex obj); }; Complex::Complex() { re = 0; im = 0; } Complex::Complex(double x) { re = x; im = 0; } Complex::Complex(double x, double y){ re = x; im = y; } Complex::Complex(const Complex& obj){ re = obj.re; im = obj.im; } void Complex::show() const{ if (im >= 0) std::cout << re << "+" << im << "i" << endl; else if (im < 0) std::cout << re << im << "i" << endl; else std::cout << re << endl; } void Complex::add(Complex obj) { re += obj.re; im += obj.im; } Complex add(Complex c1, Complex c2) { Complex c3; c3.re = c1.re + c2.re; c3.im = c1.im + c2.im; return c3; } bool is_equal(Complex c1, Complex c2) { if (c1.re == c2.re && c1.im == c2.im) return 1; else return 0; } double abs(Complex obj) { double ab; ab = sqrt(obj.re * obj.re + obj.im * obj.im); return ab; }
#include"Complex.h" #include<iostream> void test() { using namespace std; Complex c1(3, -4); const Complex c2(4.5); Complex c3(c1); cout << "c1="; c1.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; } int main() { test(); }
5
#pragma once #include<iostream> #include<string> #include<iomanip> using namespace std; class Uesr { public: User(string name, string password = "111111", string email = "") : na{ name }, pa{ password }, em{ email }; void set_email() { cin >> em; }; void change_passwd() { cout << "Enter old password:"; int i; for (i = 0;i < 3;i++) { string ep; cin >> ep; if (ep.compare(pa) != 0) { if (i == 2) cout << "password input error. Please try after a while." << endl; else cout << "password input error. Please re-enter again:"; } else { cout << "Enter new passwd:"; cin >> pa; cout << "new passwd is set successfully..." << endl; break; } } }; void print_info() { cout << "name:" << na << endl; string a(pa.length(), '*'); cout << "passwd:" << a << endl; cout << "email:" << em << endl; }; string na, pa, em; };
#include "User.h" #include <iostream> void test() { using std::cout; using std::endl; cout << "testing 1......\n"; User user1("Jonny", "92197", "xyz@hotmail.com"); user1.print_info(); cout << endl << "testing 2......\n\n"; User user2("Leonard"); user2.change_passwd(); user2.set_email(); user2.print_info(); cout << endl; User::print_n(); } int main() { test(); }