Sunday 17 December 2017

c++ - Overloading Sum Operator in Custom Vector Class

itemprop="text">

As an exercise to learn a little more
about dynamic memory allocation in C++, I'm working on my own
vector class. I'm running into a little difficulty overloading
the sum operator, so I thought I'd turn here to get some insight into why this doesn't
work. Here's what I have so
far:



template            T>
class vector
{
private:
T*
pointer_;
unsigned long size_;

public:
//
Constructors and destructors.
vector();
template
vector(const A&);
template vector(const A&, const
T&);
vector(const vector&);

~vector();

// Methods.
unsigned long
size();

T* begin();
T* end();

vector& push_back(const T&);

//
Operators.
T operator[](unsigned long);
vector&
operator=(const vector&);
friend vector&
operator+(const vector&, const
vector&);
};



The
template vector(const A&) constructor
looks like
this:



template
template
vector::vector(const A&
size)
{
this->pointer_ = new T[size];
this->size_
=
size;
}



Finally,
the operator+ operator looks like
this:



template            T>
vector& operator+(const vector& lhs, const
vector& rhs)
{
vector
result(lhs.size_);
for (unsigned long i = 0; i != result.size_;
i++)
{
result.pointer_[i] = lhs.pointer_[i] +
rhs.pointer_[i];

}
return
result;
}


My
compiler (VS2013) returns an unresolved external symbol error
when I try to compile this code, which (as I understand it) means href="https://stackoverflow.com/questions/9928238/unresolved-external-symbol-no-idea">there's
a function declared somewhere that I haven't actually defined. I'm not sure
where the problem is, however: the template vector(const
A&)
constructor works fine. What am I missing?



Answer




You're not properly friending the template
operator function. There are multiple ways to do this, each of which has advantages. One
is the friend-the-world ideology where all expansions of the template are friends with
each other. I prefer to be a bit more restrictive than
that.



Above your vector
class, do
this:




template            T>
class vector;

template T>
vector operator+(const vector& lhs, const
vector&
rhs);


The proceed as
before, but note the syntax in the friend
declaration:




// vector
class goes here....
template class
vector
{
.... stuff ....

friend
vector operator+<>(const vector&, const
vector&);
};


Then
define the rest as you have it. That should get you what I think you're trying to
achieve.




Best of
luck.



PS: invalid reference return value fixed
in the above code.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...