small operator question

K

Kev

As its not possible, as far as I know, to have more than one parameter in
an overloaded equality operator, is it possible to do something like this?

MyStruct A(1, 2, 3), B(4, 5, 6);

A = B; works;

A = MyStruct(4, 5, 6); does not

Thx
 
A

Alf P. Steinbach

* Kev:
As its not possible, as far as I know, to have more than one parameter in
an overloaded equality operator,

It seems you mean assignment operator.

is it possible to do something like this?

MyStruct A(1, 2, 3), B(4, 5, 6);

A = B; works;

A C++ comment can look like this:

A = B; // works

A = MyStruct(4, 5, 6); does not

In general you cannot detect that an argument is a temporary, so no, you
can not make the last construction not work except for special cases --
and why would you?
 
A

Aries Sun

"A = MyStruct(4, 5, 6); " should work, if you defined MyStruct's
constructor explicitly

Aries Sun
 
E

Earl Purple

It worked on VC7.1 even when I made the operator= take a non-const
reference:

#include <algorithm>

struct MyStruct
{
int a;
int b;
int c;
MyStruct( int x, int y, int z )
: a(x), b(y), c(z)
{
}

MyStruct& operator=( MyStruct& rhs )
{
std::swap( a, rhs.a );
std::swap( b, rhs.b );
std::swap( c, rhs.c );
return *this;
}
};

int main()
{
MyStruct A(1,2,3), B(4,5,6);
A = B;
A = MyStruct( 4, 5, 6 );
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top