对于下面的代码,出现的错误如下:
Argument of type "ThatThingThatUsesExceptions::HereBeTheError *" is not compatible with parameter of type "Exception *"
这是我实际代码中显示的完整错误:
(active) E0167 argument of type "Input::ErrorNoPinSet *" is incompatible with parameter of type "Exception *" AddingOOP c:\MyFilePathToMyRepoDir\DroneSoftware\ArduinoBasedCode\AddingOOP\Input.cpp 17
我正在为无人机编写大量代码,因此大部分代码将在微 Controller 上运行,遗憾的是微 Controller 通常不具备使用 try-catch 错误处理的能力。我试图以一种可能非常 hack-y 的方式实现它,但我遇到了一些问题。
这是正在发生的事情的一个极其简化的版本:
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()
我几乎尝试了所有我能想到的方法,包括一些看起来很愚蠢的事情,但我别无选择,因此决定尝试所有我能想到的选项。
感谢您提供的任何帮助!
最佳答案
使用 g++ 时,错误消息会更清晰一些:
prog.cpp:22:52: error: taking address of temporary [-fpermissive]
替代方法 new HereBeTheError()
可以编译,但会导致内存泄漏。
一种可行的方法是使用局部变量:
HereBeTheError a;
Exception::eThrowException(&a); //This works
您也可以通过引用而不是指针传递参数。然后你可以通过一个临时的,条件是它是一个 const 引用( demo )。
关于c++ - "Argument of Type Incompatible"来自继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47821417/