代码改变世界

this指针的应用

2016-04-27 00:37  想打架的蜜蜂  阅读(200)  评论(0编辑  收藏  举报

#include<iostream>
#include<string>

using namespace std;


class student
{
private:
    char *name;
    int id;

public:
    student(char *Name="no name",int Id=0)
    {
        int len=strlen(Name);
        name=new char[len+1];
        name[len]='\0';
        memcpy(name,Name,len);
        id=Id;
    }

    void copy(const student& ss)
    {
        if(this==&ss)
        {
            cout<<"你不能复制自身"<<endl;
        }
        else
        {
            delete []name;
            int len=strlen(ss.name);
            name=new char[len+1];
            name[len]='\0';
            memcpy(name,ss.name,len);
            id=ss.id;
        }
    }

    void print()
    {
        cout<<"name: "<<name<<" id: "<<id<<endl;
    }

    ~student()
    {
        delete []name;
        name==NULL;
    }
};

int main()
{
    student st1("dingling",001);
    student st2("zhx",002);
    st1.print();
    st2.print();
    st2.copy(st1);
    st2.copy(st2);
    st1.print();
    st2.print();
    cin.get();
    return 0;
}