Operator overloading

Hey guys, I am working on an assignment in which i have to perform th following task
1
2
myClass itsObject1,itsObject2;
itsObject2=5000+itsObject1;


i have defined overloaded operator as follows in the header file but in the cpp file of the class it gives error.
 
friend vli &vli::operator + (int &a,vli &obj);


help me how to define it in cpp file of my class?
friend vli &vli::operator + (int &a,vli &obj);
Since operator+ is defined as a friend it will not be a member of vli.
And also, you cannot return a reference to vli

The proper way to define is :
1
2
3
4
vli operator+ ( int &a, const vli &obj )
{
    // ...
}


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
#include <iostream>

struct Int {
    Int() { }
    explicit Int( int num ) : n_(num) { }
    Int& operator= ( const Int& num ) { n_ = num.n_; return *this; }
    
    int get() const { return n_; } // no need to make operator+ friend if u have accessor
    
private :
    friend Int operator+ ( int lhs, const Int& rhs ); // cannot return a reference to Int
    
    int n_;
};

// ~~ CPP :
Int operator+ ( int lhs, const Int& rhs ) // cannot return a reference to Int
{ return Int( lhs + rhs.n_ ); }

int main()
{
    Int i( 100 );
    Int j;
    
    j = 123 + i;
    
    std::cout << j.get(); // 223
}
Topic archived. No new replies allowed.