Where is error?

# include <iostream>

using namespace std;

class A{
private :
int x;
public:
A():x(0){};
A(const A& oz); //copy constructor

A& operator=(const A& oz);

A operator+(const A& oz) ;

A(int t)
{
x=t;
}
};

A& A:: operator = ( const A & oz )
{
if ( this != &oz )
{
x = oz.x;
}
return * this;
}

A A:: operator + ( const A & oz )
{
A res( x + oz.x );
return res;
}

A:: A(const A& oz) { //copy constructor
x = oz.x;
}


int main()
{
A obj1,obj2(2);
obj1=obj2;
obj1=obj2+3; //Error was here

system("pause");

return 0;
}
Last edited on
You don't have
 
A operator+(int val)
From what I've read in other topics you should never use...

system('pause');

It is OS dependent and not worth using!!!!

Here is a more descriptive link:
http://www.cplusplus.com/forum/articles/11153/

EDIT: And plus use the "code" tags to display your code!!
Last edited on
I wrote code but program didn't work.
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
55
56
57
58
59
# include <iostream>

using namespace std;

class A{
private :
int x;
public:
A():x(0){}; 
A(const A& oz); //copy constructor

A& operator=(const A& oz);

A operator+(int val);


A operator+(const A& oz) ; 

A(int t)
{
x=t;
}
};

A& A:: operator = ( const A & oz )
{
if ( this != &oz )
{
x = oz.x;
}
return * this;
}

A A:: operator + ( const A & oz )
{
A res( x + oz.x );
return res;
}

A:: A(const A& oz) { //copy constructor
x = oz.x;
}

A operator+(int val)
{
                
                //How i can write code?
                return *this;
}

int main()
{
A obj1,obj2(2);
obj1=obj2;
obj1=obj2+3; 


return 0;
}
Have you looked at this code very hard? It should be fairly obvious what the plus operator should do.
Have you looked at this code very hard? It should be fairly obvious what the plus operator should do.

Yes this problem is diffucult for me. operator overloading I don't know.
well it's a plus symbol, and overloading is used for classes... so you need to add the two objects together so to speak. The point is it's up to you how or what methods/variables you want to add together. See the tutorial on this site for more info.
1
2
3
4
5
A operator+(int val)
{
    this.x += val;
    return *this;
}
Thank you my friends!
Code has changed but the idea has not changed.
at the end of the problem solved :)

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
# include <iostream>
using namespace std;
class A{
private :
int x;
int y;
public: 
A operator+(A p) const;
 
A () 
{
x=1;
y=1;
};
 
int getx()
{
return x; 
}
 
A(int n): x(n){}; 
A(int n,int m): x(n),y(m){}; 
 
};
A A::operator+(A p) const {
return A(x+p.x);} 
 
int main()
{
A a(10, 20); 
A b;
A c =a+b+3;
cout<<c.getx()<<" ";
return 0;
}
Topic archived. No new replies allowed.