Matthew Cook wrote:
Quote:
I would like to overload the unary minus operator so that I can negate
an instance of a class and pass that instance to a function without
creating an explicit temporary variable. Here is an example:
>
#include <iostream>
using namespace std;
>
class Object
{
public:
int number;
Object(int value);
const Object operator- ();
Why are you returning a "const Object" ? You may as well return an Object.
I also suspect that "- OBJ" should not change OBJ. So operator- should
be a const function.
i.e.
Object operator- () const;
Quote:
//friend const Object operator- (const Object& o);
>
};
>
Object::Object(int value) :
number (value)
{}
>
const Object Object::operator- ()
Object operator- () const
Quote:
{
cout << "using class minus" << endl;
number = -number;
Can't be messing with number.
Return a different Object.
return Object( -number );
Quote:
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/
>
void useAnObject(Object& o)
If you want to accept references to temporaries as arguments, you must
make them "const" temporaries.
void useAnObject(const Object& o)
Quote:
{
cout << "using object with number: " << o.number << endl;
}
>
int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}
>
When I compile this, I get the following errors (gcc 4.0.1):
c++ unaryminus.cpp -o unaryminus
unaryminus.cpp: In function 'int main(int, char**)':
unaryminus.cpp:39: error: invalid initialization of non-const reference
of type 'Object&' from a temporary of type 'const Object'
unaryminus.cpp:31: error: in passing argument 1 of 'void
useAnObject(Object&)'
>
I have tried various combinations of returning void, returning const
Object, returning non-const Object, returning reference to Object, etc,
but i get similar errors. Is there a way to do this?
#include <iostream>
using namespace std;
class Object
{
public:
int number;
Object(int value);
Object operator- () const;
//friend const Object operator- (const Object& o);
};
Object::Object(int value) :
number (value)
{}
Object Object::operator- () const
{
cout << "using class minus" << endl;
return Object( -number );
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/
void useAnObject(const Object& o)
{
cout << "using object with number: " << o.number << endl;
}
int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}