C++ 构造函数中的创建的数组内存地址相同

查看:185
本文介绍了C++ 构造函数中的创建的数组内存地址相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

代码很短,直接贴上:

#include <iostream>
using namespace std;

class numbered
{
public:
    numbered()
    {
        int a[3] = {0, 0, 0}; // 每次构造函数所显示a的地址都是一样
        a[0] = num++;
        a[1] = a[0] + 1;
        a[2] = a[1] + 1;
        num = a[2] + 1;
        mysn = a;    // 明明有这个指针接手,为什么a的地址每次初始化还是一样?
    }

    static int num;
    int *mysn;
};

void f(numbered s)
{
    for (int i = 0; i != 3; i++)
        cout << s.mysn[i] << endl;
}

int numbered::num = 1;

int main(void)
{
    numbered a;
    numbered b;
//    numbered c;

    f(a);
    f(b);
//    f(c);
    return 0;
}

运行结果:

4
5
6
4
5
6

设想的是

1
2
3
4
5
6

Update:

#include <iostream>
using namespace std;

class numbered
{
public:
    numbered()
    {
        mysn = new int[3];
        mysn[0] = num++;
        mysn[1] = mysn[0] + 1;
        mysn[2] = mysn[1] + 1;
        num = mysn[2] + 1;
    }
    ~numbered()
    {
        delete [] mysn;
    }
    ...
};
...

int numbered::num = 1;

int main(void)
{
    numbered a;
//    numbered b;
//    numbered c;

    f(a);
//    f(b);
//    f(c);
    return 0;
}

为什么不能加析构函数呢?加了就delete两次,为什么?

解决方案

f(a)的时候产生了一个a的副本

默认情况下,你不写复制构造函数,编译器会自动为你生成一个默认的复制构造函数和operator=
默认行为类似下面这样:

numbered (const numbered& other)
{
    mysn = other.mysn;
}
numbered& operator=(const numbered& other)
{
    mysn = other.mysn;
    retun *this;
}

逐一复制数据成员的值,包括指针也指向原地址。
称为浅复制


你需要加一个复制构造函数和operator=

numbered(const numbered& other)
{
    mysn = new int[3];
    // 复制原对象数据
    for (i=0;i<3;++i)
    {
        mysn[i] = other.mysn[i];
    }
}
numbered& operator=(const numbered& other)
{
    mysn = new int[3];
    // 复制原对象数据
    for (i=0;i<3;++i)
    {
        mysn[i] = other.mysn[i];
    }
    retun *this;
}

重新new一个属于这个对象自己的空间,然后复制原对象指针成员指向的数据,称为深复制。
然后,你就可以在析构函数里delete属于自己的指针成员了。

~numbered()
{
    delete [] mysn;
}

这篇关于C++ 构造函数中的创建的数组内存地址相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆