C++ day4——C++核心(类)

作业:

  1. 整理思维导图

  1. 理解每一个课上代码

  2. 实现课上练习中Person和Stu的拷贝构造和拷贝赋值函数

  3. 完成下列类

    #include <iostream>
    #include <cstring>
    using namespace std;
    char c = '\0';
    class My_string
    {
        char *str;     //记录C风格的字符串
        int size;      //记录字符串长度
    public:
        //无参构造
        My_string(){cout<<"My_string的无参构造"<<endl;}
        //有参构造
        My_string(char str[100],int size):str(str),size(size)
        {cout<<"My_string的有参构造"<<endl;}
        //拷贝构造
        My_string(const My_string &other)
        {
            this->str=other.str;
            this->size=other.size;
            cout<<"My_string的拷贝构造"<<endl;
        }
        //拷贝赋值
        My_string &operator=(const My_string &other)
        {
            this->str=other.str;
            this->size=other.size;
            cout<<"My_string的拷贝赋值"<<endl;
            return *this;
        }
        //析构函数
        ~My_string()
        {cout<<"My_string的析构函数"<<endl;}
        //at函数
        char &my_at(int num);
        //输出
        void show();
    };
    void My_string::show()
    {
        cout<<"str="<<str<<endl;
        cout<<"size="<<size<<endl;
    }
    char &My_string::my_at(int num)
    {
        if(num>=size)
        {
            cout<<"输入错误"<<endl;
        }
        return *(str+num);
    }
    int main()
    {
        char str[100];
        cout<<"请输入字符串:"<<endl;
        cin>>str;
        int size;
        size=strlen(str);
        My_string p1(str,size);
        p1.show();
        My_string p2(p1);
        p2.show();
        My_string p3;
        p3=p2;
        p3.show();
    
        int num;
        cout<<"请输入下标"<<endl;
        cin>>num;
        cout<<p3.my_at(num)<<endl;
        return 0;
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值