Assigning array to an instance with operator overloading

Hello,

Currently, I am creating a vector-like class that holds integers. A problem is that I am working on an operator overload that allows a standard integer array to be "assigned" to an instance of my class. This means that all elements are copied into the class. The problem is, is that I do not know how to use the passed array correctly because I do not know the size of the array, thus I cannot copy any values. This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
IntArray& IntArray::operator=(int assignmentArray[])
{
    int lengthOfInputArray = sizeof(assignmentArray) / sizeof(assignmentArray[0]);
    if (lengthOfInputArray == this->GetLength())
    {
        for (int i = 0; i < this->GetLength(); ++i)
        {
            this->m_arrayPointer[i] = assignmentArray[i];
        }
    }

    return *this;
}
Last edited on
In this case this operator shall be a template functiion which accept arrays by a reference. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
template <size_t N>
IntArray& IntArray::operator=( int ( &assignmentArray )[N] )
{
    if ( N == this->GetLength() )
    {
        for (int i = 0; i < this->GetLength(); ++i)
        {
            this->m_arrayPointer[i] = assignmentArray[i];
        }
    }

    return *this;
}


Though I would change it the following way

1
2
3
4
5
6
7
8
9
10
11
12
template <size_t N>
IntArray& IntArray::operator=( int ( &assignmentArray )[N] )
{
    size_t n = std::min<size_t>( N, this->GetLength() ); 

    for ( size_t i = 0; i < n; ++i )
    {
        this->m_arrayPointer[i] = assignmentArray[i];
    }

    return *this;
}

Last edited on
Topic archived. No new replies allowed.