Search code examples
c++functionoverloadingoperator-keywordfriend

operator overloading(using binaray friend function) class has no member, and member inaccessible


While doing a youtube tutorial on operator overloading, I'm having trouble fixing an operator overloading (using friend function) error message. The message received was about, class Complex has no member "operator+" and class "Complex::real" declared at line 7 is inaccessible.

// link to the tutorial i'm struggling with https://www.youtube.com/watch?v=AlCYu_mc-T8

// the error message starts around here://

#include "stdafx.h"
#include <iostream>
using namespace std;

class Complex
{
    int real, imag;
public:
    void read();
    void show();
    friend Complex operator+ (Complex , Complex); // Friend function declaration
};

void Complex::read()
{
    cout << "Enter real value: ";
    cin >> real;
    cout << "Enter imaginary value: ";
    cin >> imag;
}

void Complex::show()
{
    cout << real;
    if (imag < 0)
        cout << "-i";
    else
        cout << "+i";
    cout << abs(imag) << endl;
}

Complex Complex::operator+(Complex c1, Complex c2)
{
    Complex temp;
    temp.real = c1.real + c2.real;
    temp.imag = c1.imag + c2.imag;
    return temp;
}

int main()
{
    Complex c1, c2, c3;
    c1.read();
    c2.read();
    c3 = c1 + c2; // invokes operator + (Complex, Complex)
    cout << "Addition of c1 and c2 = ";
    c3.show();
    return 0;
}

Solution

  • The friend is not a member. Hence, change this line:

    Complex Complex::operator+(Complex c1, Complex c2)
    

    to :

    Complex operator + (Complex c1, Complex c2)