Variable is not found in an operator method

Asked

Viewed 38 times

0

I’m studying operator overload but my code is not compiling.

    #include <iostream>

    using namespace std;

    class Complexo
    {
    public:
    int real, image;

Complexo();

Complexo(int r, int i);

Complexo operator +(Complexo& c);

};

Complexo::Complexo(int r, int i) {
   real = r;
   image = i;
}

Complexo operator +(Complexo& c) {
   Complexo x();
   x.real = real + c.real;
   x.image = image + c.image;
   return x;
}

Complexo::Complexo() {};

int main() {
   Complexo c1(1, 2);
   Complexo c2(4, 4);
   Complexo c3 = c1 + c2;

   cout << "Parte real: " << c3.real << endl;
   cout << "Parte imaginária: " << c3.image << endl;
   return 0;

 }

In the build, the error is as follows:

over.cpp: In function 'Complexo operator+(Complexo&)':
over.cpp:25: error: 'real' was not declared in this scope
over.cpp:26: error: 'image' was not declared in this scope

1 answer

0


This code is essentially copy thereof or from some other place that this site copied or from a place that copied from there, and there it is in the right way:

#include<iostream> 
using namespace std; 

class Complex { 
private: 
    int real, imag; 
public: 
    Complex(int r = 0, int i = 0)  { real = r; imag = i; } 
    Complex operator + (Complex const &obj) { 
         Complex res; 
         res.real = real + obj.real; 
         res.imag = imag + obj.imag; 
         return res; 
    } 
    void print() { cout << real << " + i" << imag << endl; } 
}; 

int main() { 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 + c2;
    c3.print(); 
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You cannot stop something that is not available to you, so to access the object the function that passes through the operator has to be within the class where these variables exist.

  • So it makes no sense to place prototype methods within a class? I have to necessarily put the whole body of function within the class so that the objects involved are accessed?

  • The way you want it, yeah.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.