mercredi 1 juillet 2015

What is wrong with this approach of copy and assignment? [duplicate]

This question already has an answer here:

#include <iostream>
#include <vld.h>

using namespace std;

class MyClass
{
private:
    int x;
    int y;
    int z;
private:
    void Copy(const MyClass & rhs) throw ()
    {
        x = rhs.x;
        y = rhs.y;
        z = rhs.z;
    }
public: 
    MyClass()
    {
        x = 0;
        y = 0;
        z = 0;
    }
    ~MyClass()
    {
        x = 0;
        y = 0;
        z = 0;
    }
    MyClass(const MyClass & rhs)
    {
        Copy(rhs);
    }
    MyClass & operator=(const MyClass & rhs)
    {
        Copy(rhs);

        return *this;
    }
    void Set(int a, int b, int c)
    {               
        x = a;
        y = b;
        z = c;
    }
    void Show(void) const 
    {
        cout<<x<<", "<<y<<", "<<z<<endl;
    }
};

int main()
{
    MyClass o1;
    o1.Set(10, 20, 30);
    o1.Show();

    MyClass o2(o1);

    o1 = o2;

    o1.Show();
}

Aucun commentaire:

Enregistrer un commentaire