请大家帮我看看这个程序,每次运行都会报错,还有就是为什么没有执行最后两行代码?


#include 
using namespace std;
class test
{
    int* p;
public:
    test(int k = 3) { p = new int(k); cout << "调构造函数\n"; }
    test(test& t)
    {
        p = new int(t.GetVal());
        cout << "调用了拷贝构造函数\n";
    }
      int GetVal(void) { return *p; }
      void Setval(int n) { *p = n; }
      void Show(void) { cout << p << " " << *p << endl; }
      ~test() { cout << "调用释放p" << endl; delete p; }
};

int main()
{
    test A1(1), A2 = A1;
    A1.Show(); A2.Show();
    A2.Setval(9); A2.Show();
    A2 = A1; A2.Show();
}

img

首先最后两行怎么没执行呢?不是输出1了吗?
最后错误的原因是,A2=A1是进行了一个浅拷贝,两个类对象的p指向了同一块内存,析构函数释放了两次,导致第二次会崩溃。你应该增加一个=操作符重载函数,进行p指针的深拷贝才行

#include <iostream>
using namespace std;
class test
{
    int* p;
public:
    test(int k = 3) { p = new int(k); cout << "调构造函数\n"; }
    test(test& t)
    {
        p = new int(t.GetVal());
        cout << "调用了拷贝构造函数\n";
    }
    void operator = (test &t)
    {
        if(p != NULL)
            delete p;
        p = new int(t.GetVal());
        cout <<"调用了=操作符\n";
    }
      int GetVal(void) { return *p; }
      void Setval(int n) { *p = n; }
      void Show(void) { cout << p << " " << *p << endl; }
      ~test() { cout << "调用释放p" << endl; delete p; }
};
 
int main()
{
    test A1(1), A2 = A1;
    A1.Show(); A2.Show();
    A2.Setval(9); A2.Show();
    A2 = A1; A2.Show();

}

这样就没事了

A2 = A1;
这个导致了引用传递,释放了2次