放在复制构造函数和=运算符重载中的内容

时间:2018-03-02 20:32:42

标签: c++

我需要为类定义一个复制构造函数和一个=运算符重载。这是代码:

#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];

};

我尝试过像

这样的事情
info = x.info;

但它只是给了我一个“表达式必须是可修改的左值”错误。

1 个答案:

答案 0 :(得分:3)

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;
};

以上编写的代码是您案例中的有效赋值运算符。

复制构造函数基本上是一样的。你想复制另一个列表(x)中的所有元素,然后将长度设置为x.length,但是你没有返回dereferenced this指针,因为它是一个复制构造函数,它不会返回任何内容。