尝试使用默认复制构造函数会生成错误

时间:2015-01-09 14:51:10

标签: c++ copy-constructor

我无法使用默认的复制构造函数。第二行产生错误。

class MyNum
{

private:

    int *numPtr;

public:

    MyNum( int num)
    {
        numPtr = new int;
        *numPtr = num;
    }

    ~MyNum()
    {
        delete numPtr;
    }

    int GetNum()
    {
        return *numPtr;
    }
};

int main()

{

    MyNum first( 5 );
    MyNum second(first); //error, use default copy constructor

    return 0;
}

但是,如果一个类没有分配内存,它可以正常工作。这与" new"?

的使用有关
class MyNum
{

private:
    int num;

public:

    MyNum( int num )
    {
        this->num = num;
    }

    ~MyNum()
    {}

    int GetNum()
    {
        return num;
    }
};

int main()
{
    MyNum first( 5 );
    cout << first.GetNum() << endl;
    MyNum second( first );
    cout << second.GetNum() << endl;
    MyNum third = second;
    cout << third.GetNum() << endl;

    return 0;
}

0 个答案:

没有答案