标题:常数据成员的深拷贝,const+字符型指针 ,如何写深拷贝的代码?
取消只看楼主
ZER0O0
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-7-14
结帖率:0
已结贴  问题点数:20 回复次数:0 
常数据成员的深拷贝,const+字符型指针 ,如何写深拷贝的代码?
程序代码:
/**
没有const。
char *name;
**/
#include <iostream>
#include <cstring>
using namespace std;

class Student
{
public:
    Student(int n,char *na,float s):no(n),score(s)
    {
        name=new char[strlen(na)+1];
        strcpy(name,na);
    }
    Student(const Student& s):no(s.no),score(s.score)
    {
        name = new char[strlen(s.name)+1];
        strcpy(name,s.name);
    }
    ~Student()
    {
        if(name!=NULL)
            delete []name;
    }
    void display()const
    {
        cout << no << " " << name << " " << score <<endl;
    }
protected:

private:
    const int no;
    char *name;
    const float score;
};

int main()
{
    const Student stu1(1,"wangming",99);
    stu1.display();
    const Student stu2(stu1);
    stu2.display();
    return 0;
}

程序代码:
/**
包含const。
const char * name;
**/
#include <iostream>
#include <cstring>
using namespace std;

class Student
{
public:
    Student(int n,char *na,float s):no(n),score(s)
    {
        name=new char[strlen(na)+1];
        strcpy(name,na);
    }
    Student(const Student& s):no(s.no),score(s.score)
    {
        name = new char[strlen(s.name)+1];
        strcpy(name,s.name);
    }
    ~Student()
    {
        if(name!=NULL)
            delete []name;
    }
    void display()const
    {
        cout << no << " " << name << " " << score <<endl;
    }
protected:

private:
    const int no;
    const char *name;
    const float score;
};

int main()
{
    const Student stu1(1,"wangming",99);
    stu1.display();
    const Student stu2(stu1);
    stu2.display();
    return 0;
}
搜索更多相关主题的帖子: const char name Student score 
2018-07-14 13:57



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-488586-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 1.801593 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved