【问题标题】:What is the problem with operator+ overload?运算符+重载有什么问题?
【发布时间】:2019-03-28 22:00:32
【问题描述】:

我遇到了问题,我不知道哪里出了问题。我需要为我的班级重载运算符+,以便可以合并两个或更多列表。

错误

Xcode 一直在说:

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

我的代码

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);
        }

【问题讨论】:

标签: c++ list operator-overloading


【解决方案1】:

根据[over.oper]/6:

操作符函数要么是非静态成员函数,要么是具有 至少一个参数,其类型是类、对类的引用、枚举或对类的引用 枚举。

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

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

因此,编译器没有实例化您的operator+ 模板,而是简单地发出错误,因为内置的 + 运算符不能对两个指针进行操作。

您不需要重载任何运算符来合并列表。您可以简单地编写一个普通函数来代替。

【讨论】:

  • 感谢您的支持。没关系,我有合并它们的功能,但重载是我作业的一部分,我必须以某种方式实现这一点。有什么想法吗?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    我通过将 operator+ 操作数从 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;
    

    感谢大家的支持!

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多