【问题标题】:Undefined reference to exception used in another function对另一个函数中使用的异常的未定义引用
【发布时间】:2014-03-23 18:08:54
【问题描述】:

我做了一个程序。不幸的是,在尝试构建它时,我在函数中遇到了一个错误:未定义对 `RzymArabException::RzymArabException(std::string) 的引用。 当我抛出一个简单的类时,比如 class Rzym{};没有错误。但是当我创建一个包含某种数据的类时(其中的构造函数和消息不起作用),如果您能指出错误所在,我将不胜感激。

#include <iostream>
#include <string>

using namespace std;

class RzymArabException{                      //wyjatki
    private:
        string message;
        int pozazakres;
    public:
        RzymArabException(string message);
        RzymArabException(int pozazakres);
        string getMessage(){return message;};   

};



class RzymArab {
    private:
        static string rzym[13];              //konwersja z arabskich na rzymskie 
        static int arab[13];

        static char rzymskie[7];
        static int arabskie[7];              //konwersja z rzymskich na arabskie
    public:
        static int rzym2arab(string);
        static string arab2rzym(int);
};


string RzymArab::rzym[13] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
int RzymArab::arab[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};

int RzymArab::arabskie[7] = {1000,500,100,50,10,5,1};
char RzymArab::rzymskie[7] = {'M','D','C','L','X','V','I'};

 string RzymArab::arab2rzym(int x){
        string s="";
     if(x<1 || x>3999)
        throw RzymArabException("Podana liczba w zapisie arabskim nie nalezy do dozwolonego przedzialu:(1..3999)");
     else{
        int i=12;

        while(x>=1){
            if(x>=arab[i]){
                x-=arab[i];
                s=s+rzym[i];
            }
            else
                i-=1;
        }
        }       
    return s;

}

【问题讨论】:

  • 该消息仅表示您尚未实现 RzymArabException(string message) 构造函数。 (更具体地说,这意味着您的程序中的某些内容正在使用该构造函数构造 RzymArabException,但链接器找不到它的定义。)
  • 我看不到您在RzymArabException 类中声明的函数的任何定义?!?

标签: c++ undefined-reference


【解决方案1】:

您需要为您的异常类方法提供定义,以便正确链接:

class RzymArabException{                      //wyjatki
private:
    string message;
    int pozazakres;
public:
    // Note the changes for the constructor methods!
    RzymArabException(string message_) : message(message_) {}
    RzymArabException(int pozazakres_) : pozazakres(pozazakres_) {}
    string getMessage(){return message;}   

};

我还建议派生任何用作异常的类以从std::exception 派生:

class RzymArabException : public std::exception {
private:
    string message;
    int pozazakres;
public:
    // ...
    // Instead of getMessage() provide the what() method
    virtual const char* what() const { return message.c_str(); }   

};

这确保任何符合标准的代码都能够捕获您的异常,而无需使用catch(...)

【讨论】:

  • 再次感谢。对于像我这样的新手,你会推荐什么书?看来网上学习效率不是很高。
  • @user3402584 本站提供list of good books,可以参考。我个人从 B. Stroustrup 的“C++ 语言”中学到的最多。 c++ tag wiki & FAQ中也有很多不错的链接。
【解决方案2】:

这是不言自明的。您没有定义该构造函数;你只是声明了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2011-09-19
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多