操作员+过载有什么问题?

What is the problem with operator+ overload?

本文关键字:什么 问题 操作员      更新时间:2023-10-16

我遇到了一个问题,我对问题所在没有任何想法。我需要为我的类重载运算符+,以便我可以合并两个和多个列表。

错误

Xcode 一直说:

二进制表达式的操作数无效("列表 *"和"列表" *')

我的代码

template <typename Type> class List {
public:
Type data;
List *next;
void set_head(Type d) {
data = d;
next = nullptr;
}
void int_print() {
cout << data << endl;
}
};
template <typename Type>
List<Type>* operator+ (List<Type> *head1, List<Type> *head2) {
List<Type> *tmp = head1, *headf = nullptr, *tmpf = nullptr;
tmpf = list_create_head(tmp, tmp->data);
headf = tmpf;
tmp = tmp->next;
while (tmp != nullptr) {
tmpf = list_create_continue(tmpf, tmp->data);
tmp = tmp->next;
}
tmp = head2;
while (tmp != nullptr) {
tmpf = list_create_continue(tmpf, tmp->data);
tmp = tmp->next;
}
return headf;
}
//problem occurs here:
else if ((c == 8) * (bonus != nullptr)) {
List<int> *mem = nullptr;
mem = head + bonus; //Here!
free(bonus);
cout << "Result of merging: " << endl;
tmp = mem;
while (tmp != nullptr) {
tmp->int_print();
tmp = tmp->next;
}
free(mem);
}

根据 [over.oper]/6:

运算符函数应为非静态成员函数或具有 至少一个参数,其类型为类、对类的引用、枚举或对 列举。

因此,您的operator+是非法的,但编译器尚未诊断这一点,因为模板未实例化(在这种情况下,标准允许但不要求编译器发出诊断)。当您尝试添加两个List<int>指针时,根据 [over.match.oper]/1:

如果表达式中运算符的操作数没有类型是类或枚举,则运算符 假定为内置运算符...

因此,编译器没有实例化operator+模板,而只是发出错误,因为内置 + 运算符无法对两个指针进行操作。

您无需重载任何运算符即可合并列表。您可以简单地编写一个普通函数来执行此操作。

不能重载operator+将 2 个指针作为输入,或返回指针作为输出。 它需要将对象引用作为输入,并按值返回一个新对象作为输出(这要求你的类支持 3/5 规则,而它目前不支持)。 您当前的类设计不太适合支持串联操作。

我通过将运算符+操作数从List*更改为简单的List来找到解决方案:

template <typename Type>
List<Type>* operator+ (List<Type> head1, List<Type> head2) {
List<Type> *tmp = &head1, *headf = nullptr, *tmpf = nullptr;
tmpf = list_create_head(tmp, tmp->data);
headf = tmpf;
tmp = tmp->next;
while (tmp != nullptr) {
tmpf = list_create_continue(tmpf, tmp->data);
tmp = tmp->next;
}
tmp = &head2;
while (tmp != nullptr) {
tmpf = list_create_continue(tmpf, tmp->data);
tmp = tmp->next;
}
return headf;
}

问题是写这样的代码不方便,但无论如何:

mem = *head + *bonus;

感谢大家的支持!