operator -- overloading

hello
don'tn know why it doesn't compile
#include <cstdlib>
#include <iostream>

using namespace std;

class A
{
public:
A(){x=0;}

A operator=(A k){return k;};
A operator-(A h){return h;};
A operator--(int){};

~A(){};

private:
int x;

};

std::ostream& operator<<(std::ostream &strm, const A &a)
{
return strm;
};

int main(int argc, char *argv[])
{
A a,b,c;
a=b(--c-a);
cout<<a;

return 0;
}
well, for the compiler b(...) looks like function call, but I guess that you mean a multiplication then the multiplication sign * is required. I.e. a=b * (--c-a);

the output is undefined by the way
Last edited on
For a start these operators are not actually acting on the object they're being called from so they're completely useless. Also I believe it's best to pass both the arguments and the return value of operators as a reference to the objects in question.
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
class A{
public:
    A& operator=(const A& arg){
        x = arg.x;
        return *this;
    }
    A& operator-(const A& arg){
        return A(x - arg.x);
    }
    //-- operator is usually short for -=1 but I'm not sure what you want here
private:
    int x;
};
It's a bad idea to return a non-const reference to a temporary.

@op: In general, the compiler will output a message about what the error is.
By instance
foo.cpp:30:6: error: no match for ‘operator--’ in ‘--c’ (operand type is ‘A’)
You have defined post-decrement but used pre-decrement.
Ya I forgot about that, I'm glad you mentioned it because I was using that in my own code...

Note to op: Pass by value for +, -, *, /, etc, and pass by reference to anything that's editing an existing copy such as +=, --, =*, etc
Topic archived. No new replies allowed.