注册 登录
编程论坛 C++教室

大牛们过来看看我的析构函数需要怎么改?

新人学习 发布于 2018-01-19 14:33, 1681 次点击
#include<iostream>
using namespace std;
//=号操作符重载 只能是成员函数 不能用全局函数
class A
{
public:
    char *p;
    int a;
    int jishu;
public:
    static int Aa;
public:
    A(char *_p = "我爱你!", int _a = 0)
    {
        p = _p;
        a = _a;
        Aa++;
        jishu = Aa;
    }
    void Display()
    {
        cout << "第" << jishu << "个对象的值:\n";
        cout << "p = " << p << " ." << " a = " << a << endl;
        cout << "第"<<jishu<<"个对象的p的地址:"<<&p << endl;
    }
    A operator=(A& Object)
    {
        if (this->p != NULL)
        {
            delete[]p;
        }
        int i;
        this->p = new char[strlen(Object.p) + 1];
        for (i = 0; i <= strlen(Object.p); i++)
            this->p[i] = Object.p[i];
        this->p[i] = '\0';
        this->jishu = Aa;
        return (*this);
    }
    ~A()
    {
        if (p != NULL)
            delete[]p;
    }
};
int A::Aa = 0;

int main()
{
    A Object1, Object2("我的", 10);
    Object1.Display();

    Object2.Display();
    A Object3 = Object2;
    Object3.Display();
    cout << A::Aa << endl;
    A Object4;
    Object4.Display();

    system("pause");
    return 0;
}

能运行 但是可能到析构函数的时候窗体都停止了 还响了下声音.
4 回复
#2
rjsp2018-01-19 16:10
与你上一个问题错得一样。
#3
新人学习2018-01-19 18:49
哎~~~我慢慢研究吧...
#4
stop12042018-01-22 10:02
用智能指针就没问题了~
#5
wj05012018-01-27 21:02
动态申请的对象,用完就删吧。。。。。析构里好像不用写东西。。。。就在构造函数里删??
1