在复制构造函数中放入什么 = 运算符重载

What to put in copy constructors and = operator overloads

本文关键字:什么 运算符 重载 复制 构造函数      更新时间:2023-10-16

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

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

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

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,但不返回取消引用的指针,因为它是一个复制构造函数,它不返回任何内容。