2

我使用多个 GCC 尝试了以下代码,但在运行使用 O1 和 gcc4.7.1 及更高版本编译的代码时遇到了问题。

#include <stdexcept>
#include <iostream>

struct Interface_1
{
    virtual void setA() = 0;
};

struct Interface_2
{
    virtual void setB() = 0;
};

struct Master: Interface_1, Interface_2
{
    void setA()
    {
        throw std::runtime_error("I was thrown");
    }
    void setB()
    {
        throw std::runtime_error("I was thrown");
    }
};

int main()
{
    Master m;
    Interface_2& i2 = m;
    try
    {
        i2.setB();
    }
    catch (const std::runtime_error& e)
    {
        std::cout << "Caught exception e=" << e.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "Did not catch exception" << std::endl;
    }

    std::cout << "Done running" << std::endl;
}

在上面的代码中,我是来自接口 Interface_2 的引用来引用 Master 类中的对象,这将导致崩溃

terminate called after throwing an instance of 'std::runtime_error'
  what():  I was thrown
Abort (core dumped)

但如果我使用来自 Interface_1 的引用,它会起作用:

int main()
{
    Master m;
    Interface_1& i1 = m;
    try
    {
        i1.setA();
    }
    catch (const Exception& e)
    {
        std::cout << "Caught exception e=" << e.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "Did not catchexception" << std::endl;
    }

    std::cout << "Done running" << std::endl;
}

我只是得到预期的结果:

Caught exception e=I was thrown
Done running

似乎我继承的第一个接口只能用于引用 Master 类的对象。我还从第一个接口继承如下:

class Master: public virtual Interface_1, public Interface_2

然后来自 Interface_2 的引用结果很好。相反,我遇到了来自 Interface_1 的引用问题。

我已经尝试过使用高达 4.9 的 g++,但我不知道它是否适用于 5.x 版本。不幸的是,我不能只是去更改编译器的版本。由于限制和限制,我应该坚持使用 4.8。因此,我想知道你们是否知道解决这个问题的任何替代/智能方法。

4

0 回答 0