首页 > 编程语言 >实验2 类和对象_基础编程2

实验2 类和对象_基础编程2

时间:2023-11-05 12:33:32浏览次数:40  
标签:std const string 对象 double void 编程 int 实验

实验任务1

demo1.dev

方法一

#ifndef T_H
#define T_H
#include <iostream>
#include <string>
using namespace std;
// 类T的声明
class T {
    public:
        T(int x = 0, int y = 0); // 带有默认形值的构造函数
        T(const T &t); // 复制构造函数
        T(T &&t); // 移动构造函数
        ~T(); // 析构函数
        void set_m1(int x); // 设置T类对象的数据成员m1
        int get_m1() const; // 获取T类对象的数据成员m1
        int get_m2() const; // 获取T类对象的数据成员m2
        void display() const; // 显示T类对象的信息
        friend void func(); // 声明func()为T类友元函数
    private:
        int m1, m2;
    public:
        static void disply_count(); // 类方法,显示当前T类对象数目
    public:
        static const string doc; // 类属性,用于描述T类
        static const int max_count; // 类属性,用于描述T类对象的上限
    private:
        static int count; // 类属性,用于描述当前T类对象数目
};
void func(); // 普通函数声明
#endif
t.h
#include "t.h"
// 类的static数据成员:类外初始化
const string T::doc {
    "a simple class"
};
const int T::max_count = 99;
int T::count = 0;
// 类T的实现
T::T(int x, int y): m1 {x}, m2 {y} {
    ++count;
    cout << "constructor called.\n";
}
T::T(const T &t): m1 {t.m1}, m2 {t.m2} {
    ++count;
    cout << "copy constructor called.\n";
}
T::T(T &&t): m1 {t.m1}, m2 {t.m2} {
    ++count;
    cout << "move constructor called.\n";
}
T::~T() {
    --count;
    cout << "destructor called.\n";
}
void T::set_m1(int x) {
    m1 = x;
}
int T::get_m1() const {
    return m1;
}
int T::get_m2() const {
    return m2;
}
void T::display() const {
    cout << m1 << ", " << m2 << endl;
}
// 类方法
void T::disply_count() {
    cout << "T objects: " << count << endl;
}
// 函数func():实现
void func() {
    T t1;
    t1.set_m1(55);
    t1.m2 = 77; // 虽然m2是私有成员,依然可以直接访问
    t1.display();
}
t.cpp
#include "t.h"
// 测试
void test() {
    cout << "T class info: " << T::doc << endl;
    cout << "T objects max_count: " << T::max_count << endl;
    T::disply_count();
    T t1;
    t1.display();
    t1.set_m1(42);
    T t2 {t1};
    t2.display();
    T t3 {std::move(t1)};
    t3.display();
    t1.display();
    T::disply_count();
}
// 主函数
int main() {
    cout << "============测试类T============" << endl;
    test();
    cout << endl;
    cout << "============测试友元函数func()============" << endl;
    func();
}
main.cpp

运行结果

方法二

#pragma once
#include <iostream>
#include <string>
using namespace std;
// 类T的声明
class T {
    public:
        T(int x = 0, int y = 0); // 带有默认形值的构造函数
        T(const T &t); // 复制构造函数
        T(T &&t); // 移动构造函数
        ~T(); // 析构函数
        void set_m1(int x); // 设置T类对象的数据成员m1
        int get_m1() const; // 获取T类对象的数据成员m1
        int get_m2() const; // 获取T类对象的数据成员m2
        void display() const; // 显示T类对象的信息
        friend void func(); // 声明func()为T类友元函数
    private:
        int m1, m2;
    public:
        static void disply_count(); // 类方法,显示当前T类对象数目
    public:
        static const string doc; // 类属性,用于描述T类
        static const int max_count; // 类属性,用于描述T类对象的上限
    private:
        static int count; // 类属性,用于描述当前T类对象数目
};
// 类的static数据成员:类外初始化
const string T::doc {
    "a simple class"
};
const int T::max_count = 99;
int T::count = 0;
// 类T的实现
T::T(int x, int y): m1 {x}, m2 {y} {
    ++count;
    cout << "constructor called.\n";
}
T::T(const T &t): m1 {t.m1}, m2 {t.m2} {
    ++count;
    cout << "copy constructor called.\n";
}
T::T(T &&t): m1 {t.m1}, m2 {t.m2} {
    ++count;
    cout << "move constructor called.\n";
}
T::~T() {
    --count;
    cout << "destructor called.\n";
}
void T::set_m1(int x) {
    m1 = x;
}
int T::get_m1() const {
    return m1;
}
int T::get_m2() const {
    return m2;
}
void T::display() const {
    cout << m1 << ", " << m2 << endl;
}
// 类方法
void T::disply_count() {
    cout << "T objects: " << count << endl;
}
// 函数func():实现
void func() {
    T t1;
    t1.set_m1(55);
    t1.m2 = 77; // 虽然m2是私有成员,依然可以直接访问
    t1.display();
}
t.hpp
#include "t.hpp"
// 测试
void test() {
    cout << "T class info: " << T::doc << endl;
    cout << "T objects max_count: " << T::max_count << endl;
    T::disply_count();
    T t1;
    t1.display();
    t1.set_m1(42);
    T t2 {t1};
    t2.display();
    T t3 {std::move(t1)};
    t3.display();
    t1.display();
    T::disply_count();
}
// 主函数
int main() {
    cout << "============测试类T============" << endl;
    test();
    cout << endl;
    cout << "============测试友元函数func()============" << endl;
    func();
}
main.cpp

运行结果

实验任务2

demo2.dev

#pragma once
// Employee类的定义
#include <iostream>
#include <string>
#include <iomanip>
using std::string;
using std::cout;
using std::endl;
using std::setfill;
using std::setw;
using std::left;
using std::right;
using std::to_string;
struct Date {
    int year;
    int month;
    int day;
};
// Employee类的声明
class Employee {
    public:
        Employee();
        Employee(string name0, double salary0, int y, int m, int d = 1);
        void set_info(string name0, double salary0, int y, int m, int d = 1);
// 设置雇员信息
        string get_name() const; // 获取雇员姓名
        double get_salary() const; // 获取雇员薪水
        void display_info() const; // 显示雇员信息
        void update_salary(double s); // 更新雇员薪水
        void update_hire_date(int y, int m, int d); // 更新雇佣日期
        void raise_salary(double by_percent); // 计算提薪加成
    public:
        static void display_count(); // 类方法,显示雇员总数
    private:
        string id; // 雇员工号
        string name; // 雇员姓名
        double salary; // 雇员薪水
        Date hire_date; // 雇员雇佣日期
    public:
        static const string doc; // 类属性,用于描述类
    private:
        static int count; // 类属性,用于记录雇员总人数
};
const string Employee::doc {
    "a simple Employee class"
};
int Employee::count = 0;
// 默认构造函数
Employee::Employee(): id { to_string(count+1) } {
    ++count;
}
// 带参数的构造函数
Employee::Employee(string name0, double salary0, int y, int m, int d):
    id {to_string(count+1)}, name {name0}, salary {salary0},
hire_date {y, m, d} {
    ++count;
}
// 设置员工信息
void Employee::set_info(string name0, double salary0, int y, int m, int d) {
    name = name0;
    salary = salary0;
    hire_date.year = y;
    hire_date.month = m;
    hire_date.day = d;
}
// 获取员工姓名
string Employee::get_name() const {
    return name;
}
// 获取员工薪水
double Employee::get_salary() const {
    return salary;
}
// 显示雇员信息
void Employee::display_info() const {
    cout << left << setw(15) << "id: " << id << endl;
    cout << setw(15) << "name: " << name << endl;
    cout << setw(15) << "salary: " << salary << endl;
    cout << setw(15) << "hire_date: " << hire_date.year << "-";
    cout << std::right << setfill('0') << setw(2) << hire_date.month << "-"
         << setw(2) << hire_date.day;
    cout << setfill(' '); // 恢复到默认空格填充
}
// 更新薪水
void Employee::update_salary(double s) {
    salary = s;
}
// 更新雇佣日期
void Employee::update_hire_date(int y, int m, int d) {
    hire_date.year = y;
    hire_date.month = m;
    hire_date.day = d;
}
// 雇员提薪加成
// by_percent是提升比例
void Employee::raise_salary(double by_percent) {
    double raise = salary * by_percent / 100;
    salary += raise;
}
// 类方法
// 显示雇员总数
void Employee::display_count() {
    cout << "there are " << count << " employees\n";
}
empolyee.hpp
#include "Employee.hpp"
#include <iostream>
// 测试:Employee类
void test() {
    using std::cout;
    using std::endl;
    cout << Employee::doc << endl << endl;
    Employee employee1;
    employee1.set_info("Sam", 30000, 2015, 1, 6);
    employee1.update_hire_date(2019, 6, 30);
    employee1.update_salary(35000);
    employee1.display_info();
    cout << endl << endl;
    Employee employee2 {"Tony", 20000, 2023, 3, 16};
    employee2.raise_salary(15); // 提成15%
    employee2.display_info();
    cout << endl << endl;
    Employee::display_count();
}
int main() {
    test();
}
main.cpp

运行结果

实验任务3

demo3.dev

#include "Complex.h"
#include <cmath>


Complex::Complex(double r, double i) : real(r), imag(i) {}

Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}

double Complex::get_real() const {
    return real;
}

double Complex::get_imag() const {
    return imag;
}

void Complex::show() const {
    using namespace std;
    cout << real;
    if (imag != 0) {
        if (imag > 0)
            cout << " + " << imag << "i";
        else
            cout << " - " << -imag << "i";
    }
}

Complex& Complex::add(const Complex& other) {
    real += other.real;
    imag += other.imag;
    return *this;
}

Complex add(const Complex& c1, const Complex& c2) {
    Complex result(c1);
    return result.add(c2);
}

bool is_equal(const Complex& c1, const Complex& c2) {
    return (c1.real == c2.real) && (c1.imag == c2.imag);
}

double abs(const Complex& c1) {
    return sqrt(c1.real * c1.real + c1.imag * c1.imag);
}
complex.cpp
#ifndef COMPLEX_H
#define COMPLEX_H

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r = 0, double i = 0);
    Complex(const Complex& other);
    double get_real() const;
    double get_imag() const;
    void show() const;
    Complex& add(const Complex& other);
    friend Complex add(const Complex& c1, const Complex& c2);
    friend bool is_equal(const Complex& c1, const Complex& c2);
    friend double abs(const Complex& c1);
};

#endif
complex.h
#include <iostream>
#include "Complex.h"

using namespace std;

void test() {
    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) = " << 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();
}
main.cpp

实验任务4

#ifndef USER_HPP
#define USER_HPP

#include <iostream>
#include <string>

class User {
private:
    std::string name;
    std::string passwd;
    std::string email;
    static int n;

public:
    User(const std::string& username, const std::string& password = "111111", const std::string& mail = "")
        : name(username), passwd(password), email(mail) {
        n++;
    }

    void set_email() {
        std::cout << "Enter email address: ";
        std::cin >> email;
        std::cout << "Email is set successfully..." << std::endl;
    }

    void change_passwd() {
        std::string old_password, new_password;
        int attempts = 0;

        std::cout << "Enter old password: ";
        std::cin >> old_password;

        while (old_password != passwd) {
            attempts++;
            if (attempts >= 3) {
                std::cout << "Password input error. Please try after a while." << std::endl;
                return;
            }
            std::cout << "Password input error. Please re-enter again: ";
            std::cin >> old_password;
        }

        std::cout << "Enter new password: ";
        std::cin >> new_password;
        passwd = new_password;
        std::cout << "Password changed successfully." << std::endl;
    }

    void print_info() {
        std::cout << "name:   " << name << std::endl;
        std::cout << "passwd: ";
        for (size_t i = 0; i < passwd.length(); ++i) {
            std::cout << '*';
        }
        std::cout << std::endl;
        std::cout << "email: " << email << std::endl;
    }

    static void print_n() {
        std::cout << "there are " << n << " users." << std::endl;
    }
};

int User::n = 0;

#endif // USER_HPP
user.hpp
#include "User.hpp"
#include <iostream>

void test() {
    using std::cout;
    using std::endl;

    cout << "testing 1......." << endl;
    User user1("Jonny", "92197", "[email protected]");
    user1.print_info();
    cout << endl << "testing 2......" << endl << endl;
    User user2("Leonard");
    user2.change_passwd();
    user2.print_info(); // Output after changing password
    user2.set_email();
    user2.print_info(); // Output after setting email
    cout << endl;
    User::print_n();
}


int main() {
    test();
    return 0;
}
task4.cpp

运行结果

#include <iostream>
#include <string>
#include <vector>

class User {
private:
    std::string name;
    std::string passwd;
    std::string email;
    static int n;

public:
    User(const std::string& username, const std::string& password = "111111", const std::string& mail = "")
        : name(username), passwd(password), email(mail) {
        n++;
    }

    void set_email() {
        std::cout << "Enter email address: ";
        std::cin >> email;

        while (!is_valid_email(email)) {
            std::cout << "Invalid email address. Please enter a valid email: ";
            std::cin >> email;
        }

        std::cout << "Email is set successfully..." << std::endl;
    }

    void change_passwd() {
        std::string old_password, new_password;
        int attempts = 0;

        std::cout << "Enter old password: ";
        std::cin >> old_password;

        while (old_password != passwd) {
            attempts++;
            if (attempts >= 3) {
                std::cout << "Password input error. Please try after a while." << std::endl;
                return;
            }
            std::cout << "Password input error. Please re-enter again: ";
            std::cin >> old_password;
        }

        std::cout << "Enter new password: ";
        std::cin >> new_password;

        while (!is_valid_password(new_password)) {
            std::cout << "Invalid password. Password must be at least 6 characters. Enter new password: ";
            std::cin >> new_password;
        }

        passwd = new_password;
        std::cout << "Password changed successfully." << std::endl;
    }

    void print_info() {
        std::cout << "name:   " << name << std::endl;
        std::cout << "passwd: " << std::string(passwd.size(), '*') << std::endl;
        std::cout << "email: " << email << std::endl;
    }

    static void print_n() {
        std::cout << "there are " << n << " users." << std::endl;
    }

private:
    bool is_valid_email(const std::string& email) {
        return email.find('@') != std::string::npos;
    }

    bool is_valid_password(const std::string& password) {
        return password.length() >= 6;
    }
};

int User::n = 0;

void test1() {
    std::string s1{"hello"};
    std::string s2(s1.size(), '*');
    std::cout << "s1: " << s1 << std::endl;
    std::cout << "s2: " << s2 << std::endl;
}

void test2() {
    std::vector<std::string> v{"[email protected]", "xyz.gmail.com"};
    bool is_valid;
    for (auto &s : v) {
        auto pos = s.find("@");
        if (pos == std::string::npos)
            is_valid = false;
        else
            is_valid = true;
        std::cout << s << "\t" << std::boolalpha << is_valid << std::endl;
    }
}

int main() {
    std::cout << "测试1:" << std::endl;
    test1();
    std::cout << "\n测试2:" << std::endl;
    test2();
    
    return 0;
}
View Code

运行结果

实验任务5

# ifndef __ACCOUNT_H__
# define __ACCOUNT_H__
class SavingsAccount {
    private:
        int id;
        double balance;
        double rate;
        int lastDate;
        double accumulation;
        static double total;

        void record(int date, double amount);

        double accumulate(int date) const {
            return accumulation+balance * (date-lastDate);
        }
    public:
        SavingsAccount(int date, int id, double rate);
        int getld() const {
            return id;
        }
        double getBalance() const {
            return balance;
        }
        double getRate() const {
            return rate;
        }
        static double getTotal() {
            return total;
        }
        void deposit (int date, double amount) ;
        void withdraw(int date, double amount);
        void settle(int date);
        void show() const;
};

#endif
account.h
# include "account.h"
# include <cmath>
# include <iostream>
using namespace std;

double SavingsAccount::total= 0;
SavingsAccount::SavingsAccount(int date, int id, double rate)
    : id(id) , balance(0),rate(rate), lastDate(date),accumulation(0) {
    cout<<date<<"\t#”<<id<<” is created"<<endl;
}
void SavingsAccount::record(int date, double amount) {
    accumulation=accumulate(date);
    lastDate=date;
    amount=floor (amount * 100+ 0.5) /100;           
    balance+=amount;
    total+=amount;
    cout<<date<<"\t# "<< id<< "\t " << amount<<"\t"<<balance<<endl;
}


void SavingsAccount::deposit(int date, double amount) {
    record(date, amount);
}
void SavingsAccount::withdraw (int date, double amount) {
    if (amount>getBalance())
        cout<< "Error: not enough money"<<endl;
    else
        record(date,-amount);
}
void SavingsAccount::settle (int date) {
    double interest= accumulate (date) * rate/365; 
    if (interest!=0)
        record(date, interest);
    accumulation= 0;
}
void SavingsAccount::show() const {
    cout<<"#"<<id<< "\tBalance: "<<balance;
}
account.cpp
#include "account.h"
#include <iostream>
using namespace std;

int main () {
    SavingsAccount sa0(1, 21325302, 0.015);
    SavingsAccount sa1(1, 58320212, 0.015);
    sa0.deposit (5, 5000);
    sa1.deposit(25, 10000);
    sa0.deposit(45, 5500);
    sa1.withdraw(60, 4000);
    sa0.settle(90);
    sa1.settle(90);
    sa0.show () ; cout<<endl;
    sa1.show () ; cout<<endl;
    cout<< "Total: "<<SavingsAccount::getTotal () <<endl;
    return 0;
}
5_11.cpp

 运行结果

标签:std,const,string,对象,double,void,编程,int,实验
From: https://www.cnblogs.com/le-sh/p/17767018.html

相关文章

  • 实验3
    实验1源代码1#include<stdio.h>2#include<stdlib.h>3#include<time.h>4#include<windows.h>5#defineN8067voidprint_text(intline,intcol,chartext[]);8voidprint_spaces(intn);9voidprint_blank_lines(intn);10......
  • 实验3 类与数组、指针
    实验任务1point.hpp#pragmaonce#include<iostream>usingstd::cout;usingstd::endl;classPoint{public:Point(intx0=0,inty0=0);~Point()=default;intget_x()const;intget_y()const;voidshow()const;voidmov......
  • 19.网络编程之网络基础概念
    19.网络编程之网络基础概念学习目标了解OSI七层、TCP/IP四层模型结构了解常见网络协议格式掌握网络字节序和主机字节序之间的转换(大端法和小端法)说出TCP服务器端通信流程说出TCP客户端通信流程独立写出TCP服务器端代码独立写出TCP客户端代码1.网络基础概......
  • 【教3妹学编程-算法题】使数组变美的最小增量运算数
    2哥 :3妹,脸上的豆豆好了没呢。3妹:好啦,现在已经没啦2哥 :跟你说很快就会消下去的,还不信~既然你的容颜和心情都如此美丽,那我们就再做一道关于美丽的题吧。3妹:切,2哥就会取笑我,伤心时让我做题,开心时也让我做题! 1题目: 给你一个下标从0开始、长度为n的整数数组nums,和一个整......
  • 有趣的Java之网络多线程——UDP编程
    UDP编程通信基本介绍类DatagramSocket和DatagramPacket【数据包/数据报】实现了基于UDP协议网络程序。UDP数据报通过数据报套接字DatagramSocket发送和接收,系统不保证UDP数据报一定能安全送到目的地,也不确信什么时候可以抵达。DatagramPacket对象封装了UDP数据报,在数据报中包含了发......
  • 一文读懂ReentrantLock在多线程编程中的作用和优点
    引言在当今这个数字化时代,软件开发已经离不开多线程编程。但是,多线程编程也带来了一系列复杂性和挑战,其中最关键的一个问题就是线程同步和互斥。为了应对这个问题,Java语言提供了一些工具,其中最强大的工具之一就是ReentrantLock。本文将对ReentrantLock进行深入探讨,介绍它在多线程编......
  • 实验三 类与数组、指针
    实验任务1task1.cpp源码:Point.hpp:1#pragmaonce23#include<iostream>4usingstd::cout;5usingstd::endl;67classPoint{8public:9Point(intx0=0,inty0=0);10~Point()=default;1112intget_x()const;13......
  • 实验3
    任务1源代码1#include<stdio.h>2#include<time.h>3#include<windows.h>4#include<stdlib.h>5#defineN806voidprint_line(intn);7voidprint_col(intn);8voidprint_text(intline,intcol,chartext[]);9intmain(){10......
  • 面向对象和面向过程
    面向对象,里面的“面向”是什么意思呢,“面向”的意思就是面对着,面向对象,就是你看到的都是对象,比如你做一顿午饭,面向对象的就是:盖浇饭,茶水面向过程的话就是:炒饭+米饭+炒菜 所以这里的面向,是程序员面向,从程序员视角看到的世界,如果看到的是一个个对象,那就是面向对象,如果看到的是一......
  • JUC并发编程学习笔记(十)线程池(重点)
    线程池(重点)线程池:三大方法、七大参数、四种拒绝策略池化技术程序的运行,本质:占用系统的资源!优化资源的使用!->池化技术(线程池、连接池、对象池......);创建和销毁十分消耗资源池化技术:事先准备好一些资源,有人要用就拿,拿完用完还给我。线程池的好处:1、降低资源消耗2、提高相......