【问题标题】:C++ error: no matching constructor for initialization of "my:Library" with Clang 11.0.3C++ 错误:没有用于使用 Clang 11.0.3 初始化“my:Library”的匹配构造函数
【发布时间】:2020-11-08 17:07:42
【问题描述】:

我已经发布了几篇与我的问题类似的帖子,但我不知道如何在我的实现中解决它。

这是关于一个自定义异常类,它可以在带有 gcc 9 的 Linux 中完美编译,但在带有 Clang 11.0.3 的 MacOs (Catalina) 中却严重失败。

代码如下:

    #include <stdexcept>
        
    class Exception : public std::runtime_error
  {
    public:
        Exception() : std::runtime_error("mt library error") {}
        Exception(const std::string& what_arg) : std::runtime_error(what_arg) {}
    };
    
    
    /// Division by zero exception.
    class ZeroDivide : public Exception
    {
    public:
        ZeroDivide() : Exception("Division by near-zero value") {}
    };

在 MacOS 中编译时出现错误:

error: no matching constructor for initialization of 'mt::Exception'
    ZeroDivide() : Exception("Division by near-zero value") {}
                   ^         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

以及不同的注释,例如:

candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [36]' to 'const mt::Exception' for 1st argument

当我尝试抛出异常时,来自第一个错误的其他错误如下:

Exception("Normalizing interval is ill defined")

我已经看到了一些示例,例如 this 如何解决问题,但我不知道如何重新实现我的以使其在 MacOs 中工作

有人可以帮助我吗?

提前致谢。

编辑

由于项目很大,我创建了一个存储库here,并带有一个最小示例来重现错误,您只需按照以下步骤进行编译

mkdir build
cd build
cmake ..
make

【问题讨论】:

  • 请尝试创建一个minimal reproducible exampleedit 你的问题来展示它。
  • @Someprogrammerdude 好的,谢谢我在我的问题中添加了一个最小的可重现示例。

标签: c++ macos constructor compiler-errors clang


【解决方案1】:

您的编译器似乎在抱怨它不会自动将您提供给Exception 的构造函数的硬编码字符串"Division by near-zero value"const char* 转换为const std::string&amp;

目前我无法访问 macos,但我的猜测是您可以通过在调用基本构造函数的位置构造 std::string 来修复它:

ZeroDivide() : Exception(std::string("Division by near-zero value")) {}

另一个可能的解决方法是在 Exception 中定义一个构造函数,该构造函数采用 const char*

Exception(const char* what_arg) : std::runtime_error(what_arg) {}

这可能是更好的解决方法,因为std::runtime_error 实际上具有const char*const std::string&amp; 的构造函数。

【讨论】:

  • 目前,第一个选项不起作用,但是第二个解决了问题。谢谢
猜你喜欢
  • 2015-07-28
  • 1970-01-01
  • 2023-03-25
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多