defining + and = operator for vector<double>

A

Amit

Hi,
I was wondering how to define the + and = operator for a vector of
double or float and do I need to define it explicitly?
does it not get defined automatically(like copy constructor) if one
does not define it explicitly?

thanks,
--A.
 
V

Victor Bazarov

Amit said:
I was wondering how to define the + and = operator for a vector of
double or float and do I need to define it explicitly?
does it not get defined automatically(like copy constructor) if one
does not define it explicitly?

The copy assignment operator does get defined automatically. However,
you still probably want to define one yourself. Read about "The Rule
of Three".

The operator+ does not get defined automatically.

As to how to define operator+, it's up to you. If you want to be able
to add a vector to another vector, then most likely you need

vector<double> operator+(vector<double> const& v1,
vector<double> const& v2)
{
if (v1.size() != v2.size())
throw "bad size";
// otherwise do what you need here: create a temporary
// vector, add values from v1 and v2 in it and then return it
vector<double> temp(v1);
// add v2 elements to each of 'temp'
return temp;
}

This should probably be a stand-alone function.

V
 
A

Amit

Thanks,
Can I define it in my own different namespace though(assuming I am
using namepspace std already)?

--A.
 
A

Alipha

Victor said:
The copy assignment operator does get defined automatically. However,
you still probably want to define one yourself. Read about "The Rule
of Three".

The operator+ does not get defined automatically.

As to how to define operator+, it's up to you. If you want to be able
to add a vector to another vector, then most likely you need

vector<double> operator+(vector<double> const& v1,
vector<double> const& v2)
{
if (v1.size() != v2.size())
throw "bad size";
// otherwise do what you need here: create a temporary
// vector, add values from v1 and v2 in it and then return it
vector<double> temp(v1);
// add v2 elements to each of 'temp'
return temp;
}

This should probably be a stand-alone function.

V
Thanks,
Can I define it in my own different namespace though(assuming I am
using namepspace std already)?

--A.

yes, however, you'd need to use:

using namespace your_namespace;

or:

using your_namespace::eek:perator+;

if you wanted to use the operator outside of your namespace. Or, you
could type, for example:

std::vector<double> result = your_namespace::eek:perator+(v1, v2);

however, that kind of defeats the purpose of defining the operator+.
Note that you should probably define operator+= too.
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top