C++ vector调用push_back提示No matching member function错误排查
问题根因
你的ab成员是std::vector<std::unique_ptr<AbstractBubble>>类型,容器存储的是指向AbstractBubble实例的独占智能指针,而你代码中直接将栈上分配的BigBubble、SmallBubble实例传入push_back,参数类型完全不匹配,因此编译器找不到对应的重载函数,抛出你遇到的报错。
另外还有隐藏问题:栈上的对象在if分支结束后就会被销毁,就算你强行把指针塞进容器,后续访问也会出现悬空指针崩溃,必须用堆分配对象配合智能指针管理生命周期。
修复方案
修改bubble_jar.cc中OnMouseEvent的对应代码,用std::make_unique创建堆实例并封装为智能指针后再存入容器:
void BubbleJar::OnMouseEvent(const graphics::MouseEvent& event) { std::cout << "BubbleJar got a MouseEvent" << std::endl; // Create a BigBubble on mouse press and a SmallBubble on mouse release // and add them to the vector. if (event.GetMouseAction() == graphics::MouseAction::kPressed) { auto b = std::make_unique<BigBubble>(event.GetX(), event.GetY(), &image_); b->Draw(); ab.push_back(std::move(b)); } else if ( event.GetMouseAction() == graphics::MouseAction::kReleased ) { auto s = std::make_unique<SmallBubble>(event.GetX(), event.GetY(), &image_); s->Draw(); ab.push_back(std::move(s)); } image_.Flush(); }
注意:std::unique_ptr是独占所有权的智能指针,不能拷贝,必须用std::move转移所有权后才能存入容器。如果你的编译器支持C++20,也可以直接用ab.emplace_back(std::make_unique<BigBubble>(...))省略move步骤。
内容的提问来源于stack exchange,提问作者hello
相关产品推荐
相关产品推荐

