将shared_ptr传递给函数不起作用
Passing shared_ptr to function is not working
我有一个名为Fan的类型,每当我尝试写这个函数时:
void connect(shared_ptr<Fan>&);
它没有被编译,这就是我在终端中得到的:
fanBook_example.cpp:34:22: error: no matching function for call to
âmtm::FanBookServer::connect(std::shared_ptr<mtm::Fan>&)â
fanBook_example.cpp:34:22: note: candidate is:
In file included from Fan.h:3:0,
from FanBookPost.h:5,
from mtm_ex4.h:36,
from fanBook_example.cpp:16:
FanBookServer.h:39:7: note: void mtm::FanBookServer::connect(int&)
我试图将sharedptr作为参数传递,但它不起作用,不知道该怎么做?谢谢
编辑:
我正在尝试实现连接函数,该函数应该以shared_ptr为例:
auto fan = std::make_shared<Fan>(1,"Bob");
server->connect(fan)
Fan类型位于Fan.h(包括在内),其内部命名空间称为mtm并且FanBookServer在名称空间mtm内。
始终从第一个编译器错误(或警告)开始,而不是最后一个。编译器错误倾向于"级联":编译器首先看到类似的东西
void connect(shared_ptr<Fan>&);
并发出类似的错误消息
test2.cc:2:14: error: no template named 'shared_ptr'; did you mean 'std::shared_ptr'?
void connect(shared_ptr<Fan>&);
^~~~~~~~~~
std::shared_ptr
根据编译器的特定版本,它很可能会用int
替换未知类型,然后继续执行它的操作——这有助于在一次运行中给出尽可能多的错误。(这并不完全是讽刺;在极少数情况下,程序会有多个独立的语法错误,程序员会很高兴一次被告知所有这些错误。)
无论如何,在您的情况下,编译器会将std::shared_ptr<Fan>
传递给原型为int&
的函数(好吧,实际上是<unknown-type>&
,但对这个编译器来说是一样的),因此它会抱怨。
在一个无关的问题上,您可能不需要通过引用传递shared_ptr
本身——只有当您计划修改调用方的指针本身时(即,如果您将其用作out参数),这才有用。您可能应该使用void connect(shared_ptr<Fan> p)
(如果它需要处理所有权问题)或void connect(const Fan& fan)
(如果它不需要处理所有权)。
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么我的数组双精度函数不起作用?
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- C++ Arduino - 随机函数不起作用
- 为什么我的数组或函数不起作用?
- 从类中的另一个文件请求函数不起作用
- 双链表堆栈删除函数不起作用
- 将 cmake 代码段转换为函数 - 不起作用
- 为什么我的从base64解码的函数不起作用?
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 子类化 STL 容器:范围构造函数不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- 以下打印树函数不起作用为什么?
- 为什么内存集函数不起作用?
- 调用填充我的主体数组的函数不起作用
- 带有自定义数字的阶乘函数不起作用
- 如何QDialog raise()函数不起作用
- Lambda 表达式闭包函数不起作用
- C++:在没有 lvalue 的情况下调用时复制构造函数不起作用