【问题标题】:Why there is compilation error for the following snippet?为什么以下代码段存在编译错误?
【发布时间】:2019-11-30 02:32:32
【问题描述】:

我收到编译错误。我无法弄清楚根本原因是什么。

我试图评论基类的构造函数/析构函数。它奏效了。 但是取消注释会导致编译错误。

#include<iostream>
using namespace std;

class BaseException{
    public:
        BaseException();
        virtual ~BaseException();
        virtual void dumpmsg() = 0;

};

class DerivedException : public BaseException
{
    public:
        DerivedException():BaseException()
        {   
        }
        void dumpmsg() override
        {
            std::cout<< "Child class exception cuaght" << std::endl;
        }   
};
void h()
{
    throw  ( DerivedException() );
}
void g()
{
    h();
}
void f()
{
    g();
}
int main()
{
    try{
        f();
    }
    catch( BaseException &ex )
    {
        ex.dumpmsg();
    }
}

错误信息:

In function `ZN16DerivedExceptionC1Ev`:
15 `undefined reference to BaseException::BaseException()`
In function `ZN16DerivedExceptionD1Ev`:
12 `undefined reference to BaseException::~BaseException()`
[Error] ld returned 1 exit status

【问题讨论】:

标签: c++ c++11 exception


【解决方案1】:

您为类BaseException 声明了默认构造函数和virtual 析构函数,但您没有提供任何定义。你需要添加

BaseException() = default;
virtual ~BaseException() = default;

或者,如果默认行为不足以满足您的需要,则可以使用函数体。请注意,virtual void dumpmsg() = 0; 在此处有所不同。它不是一个特殊的成员函数,它是纯粹的 (= 0),它允许链接器在没有定义 BaseException::dumpmsg() 的情况下完成它的工作。

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多