复制构造函数2——深入理解

//如果不显示定义复制构造函数,编译会出错,原因是:在创建对象s2时,调用默认复制构造函数并用对象s1对其进行初始化,致使s2中指针

//与s1中指针指向同一储存空间,当一个对象生命周期结束后调用析构函数释放内存空间后,另一个变量的指针悬空,无法正常使用。

//浅复制

//再用一个对象初始化另一个对象时,只复制了成员,没有复制资源(指堆内存 ,数据成员没有具体值),使两个对象同时指向同一资源,

//如果不存在资源矛盾,程序可以正常运行

#include <cstring>

#include<iostream>

using namespace std;

class Student

{

public:

    Student(int pid, char *pname, float s);

    Student(const Student& init);

    void display();

    ~Student();

private:

    int id;

    char *name;

    float score;

};

Student::Student(int pid, char * pname, float s)

{

    id = pid;

    name = new char[strlen(pname) + 1];//学会这种表达方式!!

    strcpy(name,pname);

    score = s;

}

Student::Student(const Student & init)//理解!!

{

    id = init.id;

    name = new char[strlen(init.name) + 1];

    strcpy(name, init.name);

    score = init.score;

}

void Student::display()

{

    cout << "id" << id << endl;

    cout << "name" << name << endl;

    cout << "score" << score << endl;

}

Student::~Student()

{

    delete[] name;

}

int main()

{

    Student s1(1511435, "zhanghua", 67);

    s1.display();

    Student s2 = s1;

    s2.display();

    return 0;

}图像 3

posted @ 2016-05-26 03:10  01Turing  阅读(222)  评论(0编辑  收藏  举报