如何将运算符[]与运算符=一起使用
How to use operator [] with operator =?
我对运算符[]和运算符=的对齐有问题。我无法理解如何准确地编写函数LinkedList LinkedList::operator=(const int&n(。它看起来不像是我通过电话认识的任何接线员。请帮助我理解它的性质(尽可能连同代码(。非常感谢!
文件.h
class LinkedList
{
private:
Node* pHead;
Node* pTail;
int curN;
public:
int& operator[](const int& i);
LinkedList operator = (const int& n);//
};
file.cpp
int& LinkedList::operator[](const int& i)
{
int tmp;
if (i < 0)
tmp = 0;
else if (i > this->curN)
tmp = this->curN - 1;
else
tmp = i;
int count = 0;
Node* pNode = this->pHead;
while (count < tmp)
{
count++;
pNode = pNode->pNext;
}
return pNode->_data;
}
LinkedList LinkedList::operator=(const int& n)
{
//Problem here
}
和文件main.cpp
int main()
{
srand(1234);
LinkedList l;
l[-1] = 9000;
l[4] = 2000;
l[100] = 10000;
cout << l << endl;
}
l[-1] = 9000;
l[4] = 2000;
l[100] = 10000;
在这行代码中,不会调用LinkedList::operator=(const int& n)
,因为LinkedList::operator[](const int& i)
返回对int的引用
您想要做的是在LinkedList::operator[](const int& i)
上返回一个Node,并在那里定义自己的operator=
。
Node& LinkedList::operator[](const int& i)
{
int tmp;
if (i < 0)
tmp = 0;
else if (i > this->curN)
tmp = this->curN - 1;
else
tmp = i;
int count = 0;
Node* pNode = this->pHead;
while (count < tmp)
{
count++;
pNode = pNode->pNext;
}
return *pNode;
}
///Your node class
class Node
{
public:
int _data;
Node& operator=(const int data)
{
_data = data;
return *this;
}
}
编辑:
确保将pNode放置在以后可以删除的位置,以避免内存泄漏
operator=
是为对象而不是为其内容而设的。
在这种情况下,LinkedList::operator=(const int& n)
被称为:
LinkedList l;
l = 5;
在这种情况下,只调用LinkedList::operator[]
。
l[4] = 2000;
您的赋值运算符需要在Node类中,而不是列表类中。
您正在指定给一个节点。要调用列表类分配运算符,您必须执行以下操作:
l=LinkedList((;
(但这不是你想要的(
相关文章:
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 [][] 运算符与向量一起使用?
- 不能将重载比较运算符与 Catch 测试一起使用
- 让类与运算符一起工作更简单的方法
- #define 与运算符一起使用
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 返回对象如何与分配运算符一起工作
- 将逻辑 OR 与 cout 运算符一起使用
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 我可以将 std:fixed 或 std::setprecision() 与>>运算符一起使用吗?
- 如何使 QList<Type*> 与 indexOf() 和自定义运算符==()一起使用?
- 将 std::forward 与 typeid 运算符一起使用是否有意义
- 如何将 std::<list>::reverse_iterator 与运算符 + 一起使用?
- 与类型转换运算符一起使用时条件运算符"?:"的编译器错误
- 如何将运算符[]与运算符=一起使用
- 与条件运算符一起使用时,动作不一致
- 我可以将enable_if之类的东西与隐式转换运算符一起使用吗
- 如何将运算符+和运算符=一起使用
- C++如何验证输入以与重载>>运算符一起使用
- 如何使用 std::find 与不是 std::less 的<运算符一起使用