我遇到了一些错误,我不知道如何解决。似乎我在将参数正确传递给 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> >&’
我在演示中调用is_equal的代码.cpp:
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;
}
您正在尝试传递一个需要const List &
引用的List *
指针。 只需取消引用指针即可访问所指向的对象,以便引用可以绑定到该对象:
bool random = list2->is_equal(*list3);
否则,首先不要使用new
动态分配List
对象:
List<string> list2;
List<string> list3;
...
bool random = list2.is_equal(list3);