OPERATORS???

I tried to complete the code it compiles but i am not sure if it is correct.Here it is..

// lastclass.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

class MYINT
{
int *p;
public:

MYINT(int iIn)
{
p=new int;
*p=iIn;
}


MYINT&operator=(MYINT&z){
if(!p)
p=new int;
*p=*(z.p);
return *this;
}


MYINT operator + (MYINT&z){
MYINT w(*p+*(z.p));
return w;
}
MYINT (MYINT &q){
p=new int;
*p=*(q.p);
}

MYINT():p(NULL){}
~MYINT(){
delete p;
}

};

int _tmain(int argc, _TCHAR* argv[])
{
MYINT x(12);
MYINT y(24);
x=y;

return 0;
}
Last edited on
Would you mind editing your post and putting the source inside code tags? It will make it a lot more legible and folks here will be more likely to look at it.
I don't see "p" declared in the class anywhere.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// lastclass.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

class MYINT
{
   int *p;
public: 

   MYINT(int iIn)
   {
      p=new int;
      *p=iIn;
   }

   MYINT&operator=(MYINT&z)
   {
      if(!p) p=new int;
      *p=*(z.p);
      return *this;
   }

   MYINT operator + (MYINT&z)
   {
      MYINT w(*p+*(z.p));
      return w;
   }

   MYINT (MYINT &q)
   {
      p=new int;
      *p=*(q.p);
   }

   MYINT():p(NULL){}

   ~MYINT()
   {
      delete p;
   }
};

int _tmain(int argc, _TCHAR* argv[])
{
   MYINT x(12);
   MYINT y(24);
   x=y;

   return 0;
}


Properly "tabbed" version of the original (also wrapped up in code tags).

Things I'd do differently:
MYINT(int iIn) : p(new int(iIn)) {}
1
2
3
4
MYINT operator + (MYINT&z)
{
   return MYINT(*p + *(z.p) );
}

Last edited on
Topic archived. No new replies allowed.