【问题标题】:C++ Virtual clone method, exception inheritanceC++虚拟克隆方法,异常继承
【发布时间】:2015-03-24 03:01:21
【问题描述】:

我正在我的类中创建一个虚拟克隆方法,我将在我的主文件中进行演示。但是当我尝试这样做时,我得到了错误。

这是我的课:

// includes

#include <string>
#include <exception>
#include <sstream>

namespace Vehicle_Renting {

   using namespace std;

    class Auto_Rent_Exception : public std::exception{
       protected:
          string error;
       public:
          Auto_Rent_Exception(){
          }

          virtual const string what() = 0;
          virtual ~Auto_Rent_Exception() throw();
          virtual Auto_Rent_Exception* clone() = 0;
    };

    class short_input : public Auto_Rent_Exception{
    public:
      short_input(const string errorMsg){
        stringstream ss;
        ss << errorMsg << ": short_input" << endl;
        error = ss.str();
      }
      virtual const string what(){
         return error;
      }
      virtual short_input* clone(){
         return new short_input(*this);
      }
    };
}

这是我的使用方法:

cout << "Virtual Clone" << endl;
Auto_Rent_Exception* exc = new short_input("Smthing");   //Original copy
Auto_Rent_Exception* copy;
copy = exc->clone();
cout << exc->what();
cout << copy->what() << endl;
delete exc;

我遇到了这些我不知道如何修复的错误:

undefined reference to `vtable for Vehicle_Renting::Auto_Rent_Exception'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'
undefined reference to `vtable for Vehicle_Renting::Auto_Rent_Exception'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'
undefined reference to `Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()'

Link to error image

【问题讨论】:

  • 请复制并粘贴错误文本,使其可供搜索。也就是说,我不确定 std::exception 是否可复制。但是,问题是 your 类中没有复制构造函数采用short_input&amp;。这也应该是常量,否则您无法克隆只有常量引用的对象。

标签: c++ oop inheritance methods virtual


【解决方案1】:

您尚未定义Auto_Rent_Exception::~Auto_Rent_Exception()

undefined reference to ... 错误意味着有东西被声明但没有被定义。

【讨论】:

    【解决方案2】:

    你实际上需要一个析构函数:

    virtual ~Auto_Rent_Exception()
    {
    }
    

    【讨论】:

    • 但我有析构函数:virtual ~Auto_Rent_Exception() throw();如果我改变了,我会收到关于松散抛出的错误。
    • 这只是一个析构函数的承诺,也就是声明。你仍然需要一个实现。
    猜你喜欢
    • 2015-09-09
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2016-03-26
    • 2011-01-08
    相关资源
    最近更新 更多