在复制构造函数中放入什么 = 运算符重载
What to put in copy constructors and = operator overloads
我需要为类定义一个复制构造函数和一个 = 运算符重载。代码如下:
#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,但不返回取消引用的指针,因为它是一个复制构造函数,它不返回任何内容。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 这里的 = 运算符有什么用法?
- unique_ptr < 0 或小于运算符做什么?
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 是什么让一些命名函数/运算符与众不同?
- C++,()运算符重载,它的工作是什么
- 提供运算符+或运算符到双向迭代器有什么缺点吗?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在C++中,运算符 sizeof 返回什么数据类型?
- 运算符++();调用和++(*this)有什么区别?
- 第二个常量在运算符函数中做什么?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 当值传递给C++中的运算符重载函数时会发生什么
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 在复制构造函数中放入什么 = 运算符重载
- 什么C++运算符在这里被重载了
- 当类作为参数传递给printf()时,要重载什么运算符
- 如果我想使用什么运算符" a = {x, y};"