我遇到了一些不确定的错误,我不确定该如何解决。似乎我在将参数正确传递给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;
}
答案 0 :(得分:3)
您正试图在期望引用List *
的地方传递const List &
指针。只需取消指针的引用即可访问所指向的对象,因此引用可以绑定到该对象:
bool random = list2->is_equal(*list3);
否则,首先不要使用new
动态分配List
对象:
List<string> list2;
List<string> list3;
...
bool random = list2.is_equal(list3);