【发布时间】:2020-05-21 10:04:27
【问题描述】:
我正在重载operator[]:
const Type&& operator[](int index) const {
if (index >= size) { std::cout << "Error: excessive index.\n"; return 0; }
else if (index < 0) { std::cout << "Error: negative index.\n"; return 0; }
else {
Node* temp = head->next;
for (int i = 0; i < index; i++) { temp = temp->next; }
return temp->value;
}
}
但我需要它的副本,它将返回非 const 类型值。我读到我们可以在函数参数既可以是 const 也可以是非常量的情况下使用完美转发(这样我们每次使用它时都将它们包装在 forward<Type> 中),但是如何将它用于返回的值呢?
另外,如果我只想不返回任何内容,我应该写return 0; 还是return NULL;?哪个更容易理解?
【问题讨论】:
-
返回 std::forward
(temp->value);这个呢? -
@peco
nullptr是指针的NULL,我为什么要返回它? -
是的,你是对的
-
@peco 但我不知道如何处理函数声明
const Type&& operator[],我的意思是无论如何我必须向函数声明:const 和 non-const。 -
您确定不需要只返回参考吗?完美转发主要适用于传递参数而不是返回。你也写你需要重复,这如何连接到完美的forawrding>