C++简单类的应用

第一题: 继续为 mystring类编写以下方法: 1:析构函数,释放buf指向的堆空间 2:编写 append(const mystring r) 为当前字符串尾部,拼接新的字符串r 3:编写 isEqual(const mystring r) 判断当前字符串和 字符串 r是否相等

#include <iostream>
#include <cstring>
using namespace std;

class mystring{
    char* buf;
public:
    mystring(const char* str);
    mystring();
    void show();
    void setBuf(const mystring r){
        free(this->buf);
        int len = strlen(r.buf);
        this->buf = (char*)calloc(1,len+1);
        strcpy(this->buf, r.buf);
    }
    const char* getBuf()const{
        return buf;
    }
//    ~mystring(){
//        free(buf);
//    }
    void append(const mystring r){
        int len = strlen(r.buf)+strlen(buf);
        printf("%d\n", len);
        char* temp = (char*)calloc(1, len+1);
        memcpy(temp, buf, strlen(buf));
        memcpy(temp+strlen(this->buf), r.buf, strlen(r.buf));
        printf("%s\n", temp);
        free(buf);
        buf = temp;
    }
    int isEqual(const mystring r){
        char* a = this->buf;
        char* b = r.buf;
        while(1){
            if(*a>*b){
                return 1;
            }else if(*a<*b){
                return -1;
            }else if(*a==*b && *a==0 && *b==0){
                return 0;
            }else{
                a++;
                b++;
            }
        }
    }
};



mystring::mystring(){
    buf = (char*)calloc(1,1);
}

mystring::mystring(const char* str){
    int len = strlen(str);
    buf = (char*)calloc(1,len+1);
    strcpy(buf,str);
}

void mystring::show(){
    cout << buf << endl;
}

int main()
{
    mystring ptr;
    mystring str = "hello world", r = " bye 太奶";

    ptr.setBuf(str);
    cout << ptr.getBuf() << endl;

//    ptr.setBuf("哇咔咔咔");
//    cout << ptr.getBuf() << endl;

    int n = ptr.isEqual(r);
    printf("%d\n", n);

    ptr.append(r);
    cout << ptr.getBuf() << endl;

    return 0;
}

第二题: 编写如下类: class File{ FILE* fp }; 1:构造函数,打开一个指定的文件 2:write函数 向文件中写入数据 3:read函数,从文件中读取数据,以string类型返回

#include <iostream>
#include <cstdio>
using namespace std;

class File{
    FILE* fp;
public:
    File();
    File(char* add, char* opt ){
        fp = fopen(add, opt);

    }
    ~File(){
//        fclose(rfp);
//        fclose(wfp);
    }
    void write(char buf[64]){

        fwrite(buf, 64, 1, fp);

    }
    string read(){
        char buf[64] = {0};
        fread(buf, sizeof(buf), 1, fp);
        return buf;
    }
};

int main()
{
    char add[] = "C:/Users/zackz/Desktop/C++/test.txt", opt[] = "w", optr[] = "r";
    File data(add, opt);

    char txt[64] = {0};
    cin >> txt;
    data.write(txt);

    File dat(add, optr);
    cout << dat.read() << endl;




    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值