| re: defining + and = operator for vector<double>
Victor Bazarov wrote:[color=blue]
> Amit wrote:[color=green]
> > 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?[/color]
>
> 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[/color]
Amit wrote:[color=blue]
> Thanks,
> Can I define it in my own different namespace though(assuming I am
> using namepspace std already)?
>
> --A.[/color]
yes, however, you'd need to use:
using namespace your_namespace;
or:
using your_namespace::operator+;
if you wanted to use the operator outside of your namespace. Or, you
could type, for example:
std::vector<double> result = your_namespace::operator+(v1, v2);
however, that kind of defeats the purpose of defining the operator+.
Note that you should probably define operator+= too. |