关于含指针的复制函数的一个小程序

#include<bits/stdc++.h>
using namespace std;
class Student
{
    private:
        int ID;
        char *name;
    public:
        Student(const Student &x)
        {
            ID=x.ID;
            name=x.name;//能不能理解为直接把内容存在了name本身上,而new写法name还是存地址;~A
            /*name=new char[strlen(x.name)+1]; //~B
            strcpy(name,x.name);*/
        }
        Student(int x=1,char *n="xxx")//可以思考一下为什么这里没有赋给形参一个地址;
        {
            ID=x;
            name=n;//~A
            /*name=new char[strlen(n)+1];//B
            strcpy(name,n);*/
        }
        ~Student(){
            cout<<name<<endl;
            cout<<"end"<<endl;
            delete []name;

        }
        void display()
        {
            cout<<ID<<endl<<name<<endl<<endl;

        }
};
int main()
{
    Student A(1001,"wang xiaojie");
    A.display();
    Student B(A);
    Student C;
    B.display();
    C.display();
    return 0;
}

运行结果:

    A+A  or  B+B(程序中的代号A、B)  结果理论上应该正确,A+B则输出有问题。。。 


Last:深复制主要还是在对数组、指针等含这些较复杂的数据类

型操作时使用。




猜你喜欢

转载自blog.csdn.net/qq_41661919/article/details/79830473