In my textbook, Data Structures and Algorithm Analysis in C++ (Fourth Edition) by Mark Allen Weiss, on page 106, an example is given of a user defined class called Vector. The Vector has three possible different constructors and all three of the constructors contain syntax I am unfamiliar with and that I have been having a difficult time researching. I am also unfamiliar with instances of the class Vector being the data type for "operators".
I know I have a lot of questions below so I don't expect anyone to answer them all. I am just hitting a brick wall with this problem and I need help. Even links to resources that can clarify things for me would be helpful.
Here are my questions:
1) In constructor #1, is "objects" essentially being assigned a new user defined array?
2) In constructor #2, what does it mean for the reference to have Vector as its data type? Is Vector a data type at all in the context of constructor #2's parameter?
3) In constructor #2, what does it mean for "rhs" to take "theSize" and "theCapacity" as members? Is that what is happening with instances "theSize{ rhs.theSize }" and "theCapacity{ rhs.theCapacity }"?
4) In "operator" #1, how is "Vector & operator " assigned a parameter? How can a parameter be assigned to the reference to an operator?
5) In "operator" #1, what does it mean to return "*this"?
6) Why is "objects []" deleted after operator #1?
7) In constructor #3, what does it mean for various members of "rhs" to be assigned values (as done within the brackets of the constructor )?
8) What is the difference between "&" and "&&" when not used as comparison operators?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <algorithm>
template <typename Object>
class Vector
{
public:
//constructor #1
explicit Vector( int initSize = 0 ): theSize{ initSize },
theCapacity{ initSize + SPARE_CAPACITY }
{ objects = new Object[ theCapacity ]; }
//constructor #2
Vector( const Vector & rhs ) : theSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ nullptr }
{
objects = new Object[ theCapacity ];
for( int k = 0; k < theSize; ++k )
{
objects[ k ] = rhs.objects[ k ];
}
}
//operator #1
Vector & operator= ( const Vector & rhs )
{
Vector copy = rhs;
std::swap( *this, copy );
return *this;
}
~Vector()
{ delete [ ] objects; }
//constructor #3
Vector( Vector && rhs ): theSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ rhs. objects }
{
rhs.objects = nullptr;
rhs.theSize = 0;
rhs.theCapacity = 0;
}
//operator #2
Vector & operator= ( Vector && rhs )
{
std::swap( theSize, rhs.theSize );
std::swap( theCapacity, rhs.theCapacity );
std::swap( objects, rhs.objects );
return *this;
}
/*the rest of the class are public member
functions and private member variables- all of which contain syntax I recognize*/
}
| |