沉吟丹青 2020-09-01 10:21 采纳率: 70%
浏览 74
已采纳

c++error, 求大神看一下哪里有问题

没有compile time error, 不知道哪里出了问题

#include
#include
using namespace std;

class HW1
{
public:
char *word;
HW1() { }
~HW1() {
delete [] word;
}
};

void foo(HW1 a)
{
//some operation here
}

int main()
{
HW1 a;
a.word = new char[80];
strcpy(a.word, "abc");
foo(a);
return 0;
}

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-09-01 10:37
    关注
    #include <cstring> 
    #include <iostream>
    using namespace std;
    class HW1
    {
    public:
    char *word;
    HW1() { }
    ~HW1() {
    delete [] word;
    }
    };
    void foo(HW1& a) //加上
    {
    //some operation here
    }
    int main()
    {
    HW1 a;
    a.word = new char[80];
    strcpy(a.word, "abc");
    foo(a);
    return 0;
    }
    

    否则会导致拷贝了一个对象a,作为参数,指向相同的地址,两个对象调用delete导致重复释放

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?