为什么我不能将类指针传递给访问者类?它说没有匹配的功能

Why can I not pass my class pointer to my visitor class? It says there are no matching functions

本文关键字:功能 访问者 不能 指针 为什么      更新时间:2023-10-16

本质上,这个访问者类一直在工作,直到我试图向它添加另一个类。

这是我要提到的访问者类:

访问者.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

SystemControllerSystemControllerWorker之间的唯一区别是第一个不接受任何参数,而这一个接受。知道我为什么会收到这个错误消息吗:

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&"没有已知的转换

您可能想知道为什么thisconst 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 ~~~~^