简体   繁体   中英

What to put in copy constructors and = operator overloads

I need to define a copy constructor and an = operator overload for a class. Here's the code:

#include <iostream>
#define MAXITEM 100

using namespace std;

typedef float ItemType;

class List
{
public:
    List() {};  // default constrctor

    List(const List &x) { /* what to put here */ };  // copy constructor with deep copy

    bool IsThere(ItemType item) const {};  // return true or false to indicate if item is in the 
                                        // list

    void Insert(ItemType item) {};  // if item is not in the list, insert it into the list

    void Delete(ItemType item) {};  //  delete item from the list

    void Print() { // Print all the items in the list on screen
        for (int x = 0; x < length; x++)
            cout << info[x] << " ";
        cout << "\n";
    };  

    int Length() { return length; };   // return the number of items in the list

    ~List() {};  // destructor: programmer should be responsible to set the value of all the array elements to zero

    List & operator = (const List &x) { /* and here */ };  // overloading the equal sign operator

private:
    int length;
    ItemType  info[MAXITEM];

};

I tried just doing something like

info = x.info;

but it just gives me an "expression must be a modifiable lvalue" error.

List & operator = (const List &x)
{
    //first copy all the elements from one list to another
    for(int i = 0;i < MAXITEM;i++)
        info[i] = x.info[i];
    //then set the length to be the same
    length = x.length;
    return *this;
};

The above written code is a valid assignment operator in your case.

And the copy constructor is basically the same thing. You want to copy all the elements from another list (x) and then set the length to x.length, but you don't return dereferenced this pointer, because it's a copy constructor and it doesn't return anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM