当前位置: 首页 > news >正文

2.19c++练习

1.封装一个mystring类
拥有私有成员:
    char* p
    int len
    
需要让以下代码编译通过,并实现对应功能
mystring str = "hello"
mystring ptr;
ptr.copy(str)
ptr.append(str)
ptr.show() 输出ptr代表的字符串
ptr.compare(str) 比较ptr和str是否一样
ptr.swap(str) 交换ptr 和 str的内容 

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>

using namespace std;

class mystring {
private:
    char* p;  // 用来存储字符串的指针
    int len;  // 字符串的长度

public:
    // 构造函数
    mystring(const char* str = "") {
        len = strlen(str);  // 获取字符串的长度
        p = new char[len + 1];  // 为字符串分配内存
        strcpy(p, str);  // 复制传入的字符串
        cout << "构造函数" << endl;
    }

    // 析构函数
    ~mystring() {
        delete[] p;  // 释放动态分配的内存
        cout << "析构函数" << endl;
    }

    // 拷贝函数
    void copy(const char* str) {
        delete[] p;  // 先释放当前字符串的内存
        len = strlen(str);
        p = new char[len + 1];
        strcpy(p, str);  // 复制新的字符串
    }

    // 附加函数
    void m_append(const char* str) {
        char* temp = new char[len + strlen(str) + 1];  // 为新字符串分配内存
        strcpy(temp, p);  // 复制原字符串
        strcat(temp, str);  // 追加新字符串
        delete[] p;  // 释放旧的内存
        p = temp;  // 更新指针
        len += strlen(str);  // 更新长度
    }

    // 输出函数
    void show() const {
        cout << p << endl;
    }

    // 比较函数
    bool compare(const char* str) const {
        return strcmp(p, str) == 0;  // 比较字符串是否相等
    }

    // 交换内容
    void m_swap(mystring& other) {
        swap(p, other.p);  // 交换指针
        swap(len, other.len);  // 交换长度
    }
};

int main() {
    mystring str("hello");
    mystring ptr;
    
    ptr.copy("world");  // 将 "world" 复制到 ptr
    ptr.m_append("!!!");  // 追加 "!!!" 到 ptr
    ptr.show();  // 输出 "world!!!"
    
    bool isEqual = ptr.compare("world!!!");  // 比较 ptr 和 "world!!!"
    cout << "Are they equal? " << (isEqual ? "Yes" : "No") << endl;

    ptr.m_swap(str);  // 交换 str 和 ptr 的内容
    cout << "After swap:" << endl;
    str.show();  // 输出 "world!!!"
    ptr.show();  // 输出 "hello"
    
    return 0;
}

 2.封装一个 File 类,用有私有成员
File* fp
实现以下功能
File f = "文件名" 要求打开该文件
f.write(string str) 要求将str数据写入文件中
string str = f.read(int size) 从文件中读取最多size个字节,并将读取到的数据返回
析构函数

 

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class File {
private:
    fstream* fp;  // 文件指针
    string filename;

public:
    // 构造函数,接受文件名并打开文件
    File(const string& fname) {
        filename = fname;
        fp = new fstream(filename, ios::in | ios::out | ios::app);  // 读写模式,并追加内容
        if (!fp->is_open()) {  // 如果文件不存在,则创建新文件
            fp->open(filename, ios::out);  // 先创建文件
            fp->close();
            fp->open(filename, ios::in | ios::out | ios::app);  // 重新以读写模式打开
        }
        cout << "文件 " << filename << " 打开成功!" << endl;
    }

    // 写入数据
    void write(const string& str) {
        if (fp && fp->is_open()) {
            *fp << str;  // 写入字符串
            fp->flush();  // 立即写入文件
        }
    }

    // 读取数据
    string read(int size) {
        if (!fp || !fp->is_open()) {
            return "";
        }

        fp->seekg(0, ios::beg);  // 重新定位到文件开头
        char* buffer = new char[size + 1];  // 分配缓冲区
        fp->read(buffer, size);  // 读取 size 个字节
        int bytesRead = fp->gcount();  // 获取实际读取的字节数
        buffer[bytesRead] = '\0';  // 确保字符串终止
        string result(buffer);  // 转换为字符串
        delete[] buffer;  // 释放缓冲区
        return result;
    }

    // 析构函数,关闭文件
    ~File() {
        if (fp) {
            fp->close();
            delete fp;
            cout << "文件 " << filename << " 已关闭!" << endl;
        }
    }
};

// 测试代码
int main() {
    File f("test.txt");  // 打开文件 test.txt
    f.write("Hello, world!\n");  // 写入字符串
    string content = f.read(100);  // 读取 100 字节
    cout << "读取到的内容:" << content << endl;

    return 0;
}

3.封装一个 Mutex 互斥锁类
要求:
构造函数:初始化互斥锁,并选择互斥锁的种类
lock 上锁互斥锁
unlock 解锁互斥锁
析构函数,销毁互斥锁

并且开启一个线程测试该互斥锁

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

class Mutex {
private:
    mutex mtx;  // 标准互斥锁

public:
    // 构造函数:初始化互斥锁
    Mutex() {
        cout << "Mutex 初始化成功!" << endl;
    }

    // 加锁
    void lock() {
        mtx.lock();
        cout << "Mutex 已加锁" << endl;
    }

    // 解锁
    void unlock() {
        mtx.unlock();
        cout << "Mutex 已解锁" << endl;
    }

    // 析构函数:自动销毁
    ~Mutex() {
        cout << "Mutex 已销毁" << endl;
    }
};

// 共享资源
int shared_counter = 0;
Mutex myMutex;

// 线程函数
void increment(int id) {
    for (int i = 0; i < 5; i++) {
        myMutex.lock();
        cout << "线程 " << id << " 访问共享资源" << endl;
        shared_counter++;
        cout << "当前 shared_counter 值:" << shared_counter << endl;
        myMutex.unlock();
        this_thread::sleep_for(chrono::milliseconds(100));  // 模拟耗时操作
    }
}

int main() {
    // 创建两个线程
    thread t1(increment, 1);
    thread t2(increment, 2);

    // 等待线程完成
    t1.join();
    t2.join();

    cout << "最终 shared_counter 值:" << shared_counter << endl;
    return 0;
}

 

相关文章:

  • 鸿蒙5.0实战案例:关于图像撕裂、掉帧等异常现象的原理以及优化方案
  • express-validator 数据校验详解
  • Redis未授权访问漏洞原理
  • 《Real-IAD: 用于基准测试多功能工业异常检测的真实世界多视角数据集》学习笔记
  • 【NLP算法面经】字节跳动算法岗四面详细面经(★附面题总结★)
  • 《GB∕T 43206-2023 信息安全技术 信息系统密码应用测评要求》介绍,4月1日起正式施行
  • pandas连接mysql数据库
  • JavaScript 异步编程:Promise 与 await 的关联与使用
  • Zookeeper和Kafka的依赖关系
  • Android studio如何把新项目上传到svn仓库
  • ubuntu22.4搭建单节点es8.1
  • 一个前端,如何同时联调多个后端
  • Python 库自制 Cross-correlation 算法
  • 【强化学习】随机策略的策略梯度
  • python 变量类型注释
  • 自己安装一台DeepSeek的服务器
  • 基于python实现机器学习的心脏病预测系统
  • 导出指定文件夹下的文件结构 工具模块-Python
  • PostgreSQL的学习心得和知识总结(一百六十九)|深入理解PostgreSQL数据库之 Group By 键值消除 的使用和实现
  • 【Pandas】pandas Series reindex
  • 风雨天涯梦——《袁保龄公牍》发微
  • 持续8年仍难终了的纠纷:败诉方因拒执罪被立案,胜诉方银行账户遭冻结
  • 山东省市监局“你点我检”专项抽检:一批次“无抗”鸡蛋农兽药残留超标
  • 西王食品连亏三年:主业齐“崩”,研发人员多为专科生
  • 沈阳一超市疑借领养名义烹食流浪狗,当地市监局:已收到多起投诉
  • 最美西游、三星堆遗址等入选“2025十大年度IP”