c++ - 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;
}
解决方案
您正在尝试在需要引用的List *
位置传递一个指针。const List &
只需取消引用指针即可访问被指向的对象,因此引用可以绑定到该对象:
bool random = list2->is_equal(*list3);
否则,首先不要使用动态new
分配List
对象:
List<string> list2;
List<string> list3;
...
bool random = list2.is_equal(list3);
推荐阅读
- python - 以表格形式打印嵌套列表 - Python(没有 Pandas)
- excel - 调用模块到工作表时未定义子或函数
- python - django 显示来自数据库的五个对象
- c# - 带有 AtomFeed RSS 提要的 ASP.NET 网页加载时间太长
- kernel - sys/kernel/debug/krpobes/list 为空
- c++ - 你如何在一个类中注入依赖项,它依赖于一个类,它依赖于 C++ 中的另一个类?
- nginx - 如何在 NGINX 上阻止 GET 获取特定目录?(通过推荐人或用户代理)
- wifi - 如何在 ESP32 中配置异步 Web 服务器?
- amazon-web-services - 跨多个 Lambda 函数的 AWS X-Ray 跟踪
- python - 如何根据熊猫中的其他列映射值?