-1

We just started learning about classes and operator overloading in my computing module and I have a problem with one of the examples given:

 #include <iostream>
using namespace std;

int main()
{
    class PositivePoint
    {
        // Must return PositivePoint object by value
        PositivePoint operator+(const PositivePoint& pSrc);
    };

    PositivePoint PositivePoint::operator+(const PositivePoint& pSrc)
    {
        Positive Point ret;
        ret.mX = mX + pSrc.mX;
        ret.mY = mY + pSrc.mY;
        return ret;
    }

    // Return success
    return 0;
}

I keep getting the error "unqualified-id in declaration before '(' token. I do not understand why this is the case since I thought that operator overloading was correctly defined in the above example.

JDS
  • 23
  • 4
  • Your `operator+` definition is fine. It's just that you can't define functions within other functions. Move the class, and the member function definitions outside `main`. – cigien Feb 13 '21 at 08:03

1 Answers1

0

your code is almost ok, at least with the syntax of the operator.. you need to move the class and the operator out of the main function... define mX, My and correct the typo declared for ret

after that i tested and works...

#include <iostream>
using namespace std;
class PositivePoint {
public:
    int mY;
    int mX;
    // Must return PositivePoint object by value
    PositivePoint operator+(const PositivePoint& pSrc);
};

PositivePoint PositivePoint::operator+(const PositivePoint& pSrc) {
    PositivePoint ret;
    ret.mX = mX + pSrc.mX;
    et.mY = mY + pSrc.mY;
    return ret;
}

int main() {
    PositivePoint a;
    a.mX = 1;
    a.mY = -2;
    
    PositivePoint b;
    b.mX = 3;
    b.mY = 5;
    
    PositivePoint c = a + b;
    std::cout << "Hello World!"<< std::endl;
    std::cout << "c.X: " << c.mX << std::endl;
    std::cout << "c.Y: " << c.mY << std::endl;
 
    // your code goes here
    return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Thank you so much! It makes so much more sense now (the examples we are given in class are not very illustrative). – JDS Feb 13 '21 at 11:04