2

エラーが発生します

error: expected primary-expression before ';' token

次のコードをコンパイルしようとすると。何が問題ですか?

#include <iostream>
#include <stdexcept>
#include <exception>
using namespace std;

class MyException : public std::invalid_argument{};

int main() {
    try {
        throw MyException; //here is the problem
    }
    catch (...){
    }

    return 0;
}

このコードも試しました

#include <iostream>
#include <stdexcept>
#include <exception>
using namespace std;

class MyException : public std::invalid_argument{};

int main() {
    try {
        throw MyException(); //here is the problem
    }
    catch (...){
    }

    return 0;
}

しかし、その後、別のエラーが発生します

main.cpp: In constructor ‘MyException::MyException()’:
main.cpp:6:7: error: no matching function for call to ‘std::invalid_argument::invalid_argument()’
main.cpp:6:7: note: candidates are:
In file included from main.cpp:2:0:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:86:14: note: std::invalid_argument::invalid_argument(const string&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:86:14: note:   candidate expects 1 argument, 0 provided
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:83:9: note: std::invalid_argument::invalid_argument(const std::invalid_argument&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:83:9: note:   candidate expects 1 argument, 0 provided
main.cpp: In function ‘int main()’:
main.cpp:10:27: note: synthesized method ‘MyException::MyException()’ first required here 
4

5 に答える 5

7

スローする実際のオブジェクトを作成する必要があります。

throw MyException();

括弧なしMyExceptionは単なる型であり、オブジェクトを作成しません。

于 2013-08-01T16:23:24.600 に答える
6

いくつか問題があります。

  • 基本クラスstd::invalid_argumentにはデフォルトのコンストラクターがありません。文字列を渡す必要があります。
  • パラメータを例外コンストラクタに渡すか、少なくとも呼び出す必要があります()

つまり、このようなものです。

class MyException : public std::invalid_argument {
public:
   MyException(const std::string& message) : std::invalid_argument(message) {}
};

int main() {
    try {
        throw MyException("bop"); //here is the problem
    }
...
于 2013-08-01T16:27:23.920 に答える