I know this topic might not be useful. This question can across in my mind when I was implementing friend function. In operator overloading of post-increment member function we need to write int as argument (for the sake of differentiating it from pre-increment though we don't have to pass anything) so How de we implement friend return_type operator_post-increment()?
Asked
Active
Viewed 74 times
0
-
Same as any other member/friend overloaded operator. The member function has an implicit `this` first parameter. In the friend function you need to explicitly pass the type that `this` would have been. https://stackoverflow.com/questions/4622330/operator-overloading-member-function-vs-non-member-function – JohnFilleau Apr 13 '20 at 14:48
-
Better link here. https://en.cppreference.com/w/cpp/language/operator_incdec – JohnFilleau Apr 13 '20 at 14:58
1 Answers
0
Whenever we are to implement both the functionalities of pre-increment and post-increment in the same program, we will have to write 'int' as a second argument in order to differentiate it from pre-increment operator overloading. Here below is the code for the same:
***#include<iostream>
using namespace std;
class Complex{
int real;
float imag;
public:
void setData(int R,float I)
{
real=R;
imag=I;
}
void showData()
{
if(imag<0)
cout<<real<<imag<<"j"<<endl;
else
cout<<real<<"+"<<imag<<"j"<<endl;
}
friend Complex operator-(Complex C);
friend Complex operator++(Complex C); //pre inc
friend Complex operator++(Complex C,int); //post increment
};
Complex operator-(Complex C)
{
Complex temp;
temp.real=-C.real;
temp.imag=-C.imag;
return temp;
}
Complex operator++(Complex C) //pre inc
{
Complex temp;
temp.real=++C.real;
temp.imag=++C.imag;
return temp;
}
Complex operator++(Complex C,int) //post inc
{
Complex temp;
temp.real=C.real++;
temp.imag=C.imag++;
return temp;
}
int main()
{`enter code here`
Complex c1,c2,c3;
c1.setData(2,-8.1);
c1.showData();
c2=c1++; //c2=operator++(c1); friend op post inc
c2.showData();
c3=++c1; //c3=operator++(c1); friend op pre inc
c3.showData();
}***

Pragya Sengar
- 1
- 1