C++语言基础 例程 深复制

简介: 贺老师的教学链接  本课讲解浅复制#include <iostream>using namespace std;class Test{private: int x;public: Test(int n) {x=n; } Test(const Test& c){x=c.x; } void show (){cout<&l

贺老师的教学链接  本课讲解



浅复制

#include <iostream>
using namespace std;

class Test
{
private:
    int x;
public:
    Test(int n)  {x=n; }
    Test(const Test& c){x=c.x; }
    void show (){cout<<x<<endl;}
};


int main()
{
    Test a(100);
    Test b(a);
    Test c=a;
    b.show();
    c.show();
    return 0;
}


有问题吗?
#include <iostream>
#include <cstring>
using namespace std;


class Test
{
private:
    int x;
    char *str;
public:
    Test(int n, char *s)
    {
        x=n;
        strcpy(str,s);  //肇事地点,但不是祸端
    }


    Test(const Test& c)
    {
        x=c.x;
        strcpy(str,c.str);
    }
    void show ()
    {
        cout<<x<<","<<str<<endl;
    }
};
int main()
{
    Test a(100,"Hello");
    Test b(a);
    a.show();
    b.show();
    b.show();
    return 0;
}


正解——深复制
#include <iostream>
#include <cstring>
using namespace std;


class Test
{
private:
    int x;
    char *str;
public:
    Test(int n, char *s)
    {
        x=n;
        int m=strlen(s)+1;
        str=new char[m];
        strcpy(str,s);  
    }
    Test(const Test& c)
    {
        x=c.x;
        int m=strlen(c.str);
        str=new char[m];
        strcpy(str,c.str);
    }
    ~Test()
    {
        delete str;
    }
    void show ()
    {
        cout<<x<<","<<str<<endl;
    }
};


int main()
{
    Test a(100,"Hello");
    Test b(a);
    a.show();
    b.show();
    b.show();
    return 0;
}


最危险的修改——貌似对,但一定有机会错
#include <iostream>
#include <cstring>
using namespace std;


class Test
{
private:
    int x;
    char *str;  //指针成员
public:
    Test(int n, char *s){
        x=n;
        str=s;  //不用strcpy(str,s); 
    }
    Test(const Test& c){
        x=c.x;
        str=c.str;
    }
    void show (){        
     cout<<x<<","<<str<<endl;
    }
};


int main()
{
    Test *a;
    a=new Test(100,"Hello");
    Test b(*a);
    a->show();
    b.show();
    delete a;
    b.show();
    return 0;
}


目录
相关文章
|
1月前
|
算法 编译器 C语言
C++语言的“Hello World”
C++语言的“Hello World”
14 0
|
1月前
|
编译器 C++
C++语言中const的用法
C++语言中const的用法
13 0
|
1月前
|
存储 编译器 C++
在C++语言中计算并打印出两个数的求和
在C++语言中计算并打印出两个数的求和
22 0
|
1月前
|
C++
C++语言中流程控制
C++语言中流程控制
14 0
|
1月前
|
程序员 API C语言
在C++语言的标准I/O库
在C++语言的标准I/O库
10 0
|
1月前
|
C++
在C++语言中return语句
在C++语言中return语句
20 0
在C++语言中return语句
|
1月前
|
程序员 C++ 索引
在C++语言中Vector的命名空间的作用
在C++语言中Vector的命名空间的作用
15 0
|
9天前
|
缓存 编译器 API
NumPy与其他语言(如C/C++)的接口实践
【4月更文挑战第17天】本文介绍了NumPy与C/C++的接口实践,包括Python与C/C++交互基础、NumPy的C API和Cython的使用。通过案例展示了如何将C++函数与NumPy数组结合,强调了内存管理、类型匹配、错误处理和性能优化的最佳实践。掌握这些技能对于跨语言交互和集成至关重要。
|
18天前
|
程序员 C++
C++语言模板学习应用案例
C++模板实现通用代码,以适应多种数据类型。示例展示了一个计算两数之和的模板函数`add&lt;T&gt;`,可处理整数和浮点数。在`main`函数中,展示了对`add`模板的调用,分别计算整数和浮点数的和,输出结果。
12 2
|
1月前
|
Java API 开发工具
【软件设计师备考 专题 】C、C++、Java、Visual Basic、Visual C++等语言的基础知识和应用(三)
【软件设计师备考 专题 】C、C++、Java、Visual Basic、Visual C++等语言的基础知识和应用
30 0