首页 > 解决方案 > C++ 通过引用传递?

问题描述

我遇到了一些我不知道如何修复的错误。似乎我无法正确地将参数传递给 List.h 中的类成员函数。我怎样才能解决这个问题?约束:我无法修改 is_equal 的参数或返回类型。

Demo.cpp:60:38: error: no matching function for call to ‘List<std::__cxx11::basic_string<char> >::is_equal(List<std::__cxx11::basic_string<char> >*&)’
bool random = list2->is_equal(list3);
                                  ^
In file included from Demo.cpp:1:
List.h:339:8: note: candidate: ‘bool List<T>::is_equal(const List<T>&) const [with T = std::__cxx11::basic_string<char>]’
bool is_equal(const List<T> &other) const
    ^~~~~~~~
List.h:339:8: note:   no known conversion for argument 1 from ‘List<std::__cxx11::basic_string<char> >*’ to ‘const List<std::__cxx11::basic_string<char> >&’

我在 Demo.cpp 中调用 is_equal 的代码:

List<string> *list2 = new List<string>();
List<string> *list3 = new List<string>();

// code to add values to list2 and list3

bool random = list2->is_equal(list3);    // line 60

List.h 中的 is_equal 函数:

/**
 *   description:  returns true if calling List and parameter
 *      List other contain exactly the same sequence of values.
 *      Returns false otherwise.
 *
 *  REQUIRMENT:  Linear runtime (O(n) where n is MIN(len1,len2)
 *    and len1 and len2 are the respective lengths of the two lists.
 **/
bool is_equal(const List<T> &other) const    // line 339
  {
    Node *p = front;
    int pLength = 0;
    int otherLength = 0;
    while (p != nullptr) {
      pLen++;
      p = p->next;
    }
    while (other != nullptr) {
      otherLen++;
      other = other->next;
    }
    if (pLen == otherLen)
      return true;
    return false;
  }

标签: c++data-structureslinked-list

解决方案


您正在尝试在需要引用的List *位置传递一个指针。const List &只需取消引用指针即可访问被指向的对象,因此引用可以绑定到该对象:

bool random = list2->is_equal(*list3);

否则,首先不要使用动态new分配List对象:

List<string> list2;
List<string> list3;
...
bool random = list2.is_equal(list3);

推荐阅读