【问题标题】:"Argument of Type Incompatible" from Inherited Class继承类中的“类型不兼容的参数”
【发布时间】:2018-05-29 00:27:15
【问题描述】:

在以下代码的情况下,出现的错误如下:

“ThatThingThatUsesExceptions::HereBeTheError *”类型的参数与“Exception *”类型的参数不兼容

这是我的实际代码中显示的完整错误:

(活动)“Input::ErrorNoPinSet *”类型的 E0167 参数与“Exception *”类型的参数不兼容。AddingOOP c:\MyFilePathToMyRepoDir\DroneSoftware\ArduinoBasedCode\AddingOOP\Input.cpp 17

我正在为无人机编写大量代码,因此大部分代码将在微控制器上运行,不幸的是,微控制器通常不具备使用 try-catch 错误处理的能力。我正在尝试以一种可能非常老套的方式来实现它,但我遇到了一些问题。

这是正在发生的事情的一个极其简化的版本:

class Exception
{
public:
    static void eThrowException(Exception* error)
    {
        Serial.println(error->what());
    }

    virtual const char* what();
};

class ThingThatUsesTheExceptions
{
private:
    struct HereBeTheError : public Exception { const char* what() { return "Yarrrrr me matey"; } };

protected:
    void cFunctionThatTriggersAnError()
    {
        Exception::eThrowException(&HereBeTheError()); //This is where the error occurs.
    }
};

我应该提一下,所有这些都被分割成它们自己的文件。 Exception.h 包含声明,Exception.cpp 包含定义,与 ThatThingThatUsesExceptions 相同。我不确定为什么会抛出错误。我已经尝试了许多不同的组合,将以下组合传递给 eThrowException:

&HereBeTheError()
*HereBeTheError()
new HereBeTheError()
HereBeTheError()
*new HereBeTheError()
&new HereBeTheError()

我几乎尝试了所有我能想到的东西,包括一些看起来很愚蠢的事情,但我没有选择,决定尝试所有我能想到的选择。

感谢您提供的任何帮助!

【问题讨论】:

  • 这将产生一个链接错误,因为您在没有定义的Exception 类中声明virtual const char* what();,当我将它设置为纯虚拟时,它使用 G++ 7.2 工作

标签: c++ error-handling arguments


【解决方案1】:

使用 g++ 时,错误信息会变得不那么含糊:

prog.cpp:22:52: error: taking address of temporary [-fpermissive]

替代的new HereBeTheError() 可以编译,但会导致内存泄漏。

一种可行的方法是使用局部变量:

    HereBeTheError a;
    Exception::eThrowException(&a); //This works

您也可以通过引用而不是指针传递参数。然后你可以通过一个临时的,条件是它是一个常量引用(demo)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2018-09-07
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多