C++day5(运算符重载、静态成员函数、静态成员变量、类的继承)

my_string类的运算重载 

#include 
#include 
using namespace std;

class mystring
{
private:
    char *str;   //记录C风格字符串
    int size;    //记录字符串的实际长度

public:
    //无参构造
    mystring():size(10)
    {
        str=new char[size];//构造出一个长度为10的字符串
        strcpy(str,"");//赋值为空串
    }
    //有参构造
    mystring(const char *s)
    {
        size=strlen(s);
        str=new char[size+1];
        strcpy(str,s);
    }

    //拷贝构造
    mystring (const mystring &other):str(new char[other.size+1]),
        size(other.size)
    {
        strcpy(this->str,other.str);
    }
    //析构函数
    ~mystring()
    {
        delete []str;
        str=nullptr;
    }
    //拷贝赋值函数
    mystring &operator=(const mystring &other)
    {
        if(this!=&other)
        {
            this->size=other.size;
            this->str=new char[size+1];
            strcpy(str,other.str);
        }
        return *this;
    }
    //判空函数
    bool mystring_empty(char *s)
    {
        if(strlen(s)==0)
            return 1;
        else
            return 0;
    }
    //size函数
    void mystring_size()
    {
        cout<str[pos];
    }

    //加号运算符重载
    const mystring operator+(const mystring &R)const
    {
        mystring temp;
        strcpy(temp.str,strcat(this->str,R.str));
        return temp;
    }

    //关系运算符重载(>)
    bool operator>(const mystring &R)const
    {
        if(strcmp(this->str,R.str)>=0)
            return 1;
        else
            return 0;
    }
    //加等于运算符重载
     mystring &operator+= (const mystring &R)
    {
       strcat(this->str,R.str);
        return *this;
    }

    //全局函数版完成  插入运算符   重载函数
    friend ostream &operator<<(ostream &L,const mystring &R);
    //全局函数版完成  提取运算符   重载函数
    friend istream &operator>>(istream &L,const mystring &R);


    //成员函数版实现中括号运算符
    char &operator [](const int pos)
    {
        if(pos<0||pos>size)
            cout<<"给定下标不合法"<>(istream &L,const mystring &R)
{
    L>>R.str;
    return L;
}

int main()
{
    mystring s1("hello");
    s1.show();
    s1.mystring_size();
    cout<>s5;
    cout<<"s5= "<s1)
    {
        cout<<"yes"<

继承

#include 

using namespace std;


class Person
{
protected:
    int id;    //身份证
public:
    string name;
    int age;
    Person(){cout<<"Person::无参构造"<id=other.id;
        this->name=other.name;
        this->age=other.age;
        return *this;
    }

    void show()
    {
        cout<<"id= "<

你可能感兴趣的:(c++,开发语言)