基本上这个访问者类一直在工作,直到我尝试向它添加另一个类。
这是我要引用的访问者类:
访客.h
#ifndef Visitor_h__
#define Visitor_h__
#include <stdint.h>
#include <string>
#include <vector>
namespace Ph2_System
{
class SystemController;
}
namespace GUI
{
class SystemControllerWorker;
}
class HwDescriptionVisitor
{
public:
//SystemController
virtual void visit( Ph2_System::SystemController& pSystemController ) {} //This one works
//SystemControllerWorker
virtual void visit( GUI::SystemControllerWorker& pSystemControllerWorker ) {}
}
这是试图对其进行访问的类:
SystemControllerWorker.h
#include "../HWInterface/Visitor.h"
#include "Model/settings.h"
namespace GUI
{
class SystemControllerWorker
{
public:
SystemControllerWorker(Settings &config);
~SystemControllerWorker();
void accept( HwDescriptionVisitor& pVisitor ) const {
pVisitor.visit( *this ); // this is where I get my error message
for ( auto& cShelve : fShelveVector )
cShelve->accept( pVisitor );
}
private:
Settings& m_Settings; //takes in the above &config in the contructor
SystemController
和 SystemControllerWorker
之间的唯一区别是第一个不接受任何参数,而这个有。知道为什么我会收到此错误消息:
error: no matching function for call to "HwDescriptionVisitor::visit(const GUI::SystemControllerWorker&)"
pVisitor.visit( *this );
或者这可能意味着什么?
最佳答案
有时候阅读整个错误信息是件好事,编译器真的很愿意帮助你理解它为什么会失败:
main.cpp: In member function 'void SystemControllerWorker::accept(HwDescriptionVisitor&) const':
main.cpp:15:29: error: no matching function for call to 'HwDescriptionVisitor::visit(const SystemControllerWorker&)'
pVisitor.visit(*this);
^
main.cpp:15:29: note: candidate is:
main.cpp:8:10: note: void HwDescriptionVisitor::visit(SystemControllerWorker&)
void visit(SystemControllerWorker& pSystemControllerWorker) {}
^
main.cpp:8:10: note: no known conversion for argument 1 from 'const SystemControllerWorker' to 'SystemControllerWorker&'
最后的 note
是最重要的;它说:“参数 1 没有从 'const SystemControllerWorker' 到 'SystemControllerWorker&' 的已知转换”
您可能想知道为什么 this
是 const SystemControllerWorker
类型,而不是简单的 SystemControllerWorker
。这是因为调用 pVisitor.visit(*this)
的方法本身被标记为 const
:
void accept( HwDescriptionVisitor& pVisitor ) const {
// right here ~~~~^
这使得 this
成为指向 const SystemControllerWorker
的指针,并且取消引用它也会产生 const
类型.
根据允许访问的内容,您可以从 accept
成员函数中删除 const
限定符
或
在 visit
成员函数的 SystemController&
参数中添加一个 const
限定符,如下所示:
virtual void visit( const Ph2_System::SystemController& pSystemController ) {}
// here ~~~~^
关于c++ - 为什么我不能将类指针传递给访问者类?它说没有匹配的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26299636/