操作员+过载有什么问题?
What is the problem with operator+ overload?
我遇到了一个问题,我对问题所在没有任何想法。我需要为我的类重载运算符+
,以便我可以合并两个和多个列表。
错误
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;
感谢大家的支持!
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了