实验一 类与对象

Complex.hpp

#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include<iostream>
#include<cmath>

using namespace std;

class Complex{
public:
    Complex(): real{0},imag{0} {};
    Complex(float x): real{x} {};
    Complex(float x,float y): real{x},imag{y} {};
    Complex(Complex &obj): real{obj.real},imag{obj.imag} {};
    float get_real() const{return real;}
    float get_imag() const{return imag;}
    void show() const;
    void add(const Complex &obj);
    friend Complex add(const Complex &C1,const Complex &C2);
    friend bool is_equal(const Complex &C1,const Complex &C2);
    friend float abs(Complex &obj);
private:
    float real,imag;
};

void Complex::show() const{
    if(imag>0){
        cout << real << " + " << imag << 'i';
    }
    else if(imag<0){
        cout << real << " - " << -1*imag << 'i';
    }
    else{
        cout << real;
    }
}
void Complex::add(const Complex &obj){
    real += obj.get_real();
    imag += obj.get_imag();
}

Complex add(const Complex &C1,const Complex &C2){
    Complex C3(C1.real+C2.real,C1.imag+C2.imag);
    return C3;
}
bool is_equal(const Complex &C1,const Complex &C2){
    if(C1.real==C2.real&&C1.imag==C2.imag){
        return true;
    }
    else{
        return false;
    }
}
float abs(Complex &obj){
    float a=pow(obj.real,2);
    float b=pow(obj.imag,2);
    return sqrt(a+b);
}

#endif

运行结果:

 

 User.hpp

#ifndef USER_HPP
#define USER_HPP

#include<iostream>
#include<string>

using namespace std;

class User{
public:
    User() {n++;};
    ~User() {n--;};
    User(string x): name{x} {n++;};
    User(string x,string y,string z): name{x}, passwd{y}, email{z} {n++;};
    void set_email();
    void change_passwd();
    void print_info();
    static void print_n();
private:
    string name,passwd="111111",email="";
    static int n;
};

int User::n=0;

void User::set_email(){
    cout << "请输入邮箱:" << endl;
    cin >> email;
    cout << "邮箱创建成功" << endl;
}
void User::change_passwd(){
    int n=3;
    string str;
    cout << "请输入旧密码:" << endl;
    while(n--){
        cin >> str;
        if(str!=passwd){
            if(n!=0){
                cout << "密码错误,请重新输入:" << endl;
            }
            else{
                cout << "密码错误" << endl;
            }
        }
        else{
            break;
        }
    }
    if(str!=passwd){
        cout << "错误次数过多,请稍后再试。" << endl;
    }
    else{
        cout << "请输入新密码:" << endl;
        cin >> passwd;
    }
}
void User::print_info(){
    cout << "用户名:" << name << " 密码:" << "******" << " 邮箱:" << email << endl;
}
void User::print_n(){
    cout << "用户总数:" << n << endl;
}

#endif

运行结果:

 

posted @ 2021-10-24 21:40  三面硬币  阅读(16)  评论(2编辑  收藏  举报