M
Matthew Cook
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- ();
//friend const Object operator- (const Object& o);
};
Object::Object(int value) :
number (value)
{}
const Object Object:perator- ()
{
cout << "using class minus" << endl;
number = -number;
return *this;
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/
void useAnObject(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);
}
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?
-Matthew
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- ();
//friend const Object operator- (const Object& o);
};
Object::Object(int value) :
number (value)
{}
const Object Object:perator- ()
{
cout << "using class minus" << endl;
number = -number;
return *this;
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/
void useAnObject(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);
}
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?
-Matthew