C++ - Noob - Simple Try/Catch

C++ - Noob - Simple Try/Catch

本文关键字:Catch Try Simple Noob C++      更新时间:2023-10-16

我正试图编写一个简单的try/catch语句,但我不断收到编译器错误。这是我的代码:

int divide(int x, int y)
{
    if (y == 0) {
        throw 0;
    }
    return x / y;
}
Exception::Exception()
{
    try {
        cout << divide(10, 0) << "n"; 
    } catch (int e) {
        cout << "Cannot divide by " << e << "n";
    } 
}

我得到以下编译器错误:

LNK2019:未解析的外部符号"public:int_thiscall异常::divide(int,int)"(?divide@Exception@@QAEHH@Z)在函数"public:_thiscall Exception::Exception(void)"中引用(??0Exception@@QAE@XZ)

LNK1120:1个未解析的外部

我神奇的远程调试技能告诉我divideException的成员,但您在全局命名空间中定义它。在divide前面加上Exception::,即

int Exception::divide(int x, int y)
{
    if (y == 0) {
        throw 0;
    }
    return x / y;
}

您得到的是一个链接器错误。您提到divideException类的一个成员函数,但忘记了实现它。只需使用::确认通话即可。

 cout << ::divide(10, 0) << "n";  // Take the function at global scope
                                   // This still leaves the member function implemenation
                                   // unimplemented which is bad though.

int Exception :: divide(int x, int y) { .... }