Compilation error - no matching function for call to 'Exception::Exception(Exception)'
I can not solve this problem for a while. I would be glad for some advice.
When I try to throw an exception (self created one in Java styl开发者_StackOverflowe)
throw Exception ();
compiler make a protest:
DataTypes/Date.cpp:24: error: no matching function for call to `Exception::Exception(Exception)' DataTypes/Date.cpp:24: error: in thrown expression
It does not work with any of the constructors I have. What is the problem? Here is header file of the Exception:
class Exception
{
public:
Exception(void);
explicit Exception(const char *);
explicit Exception(const Exception &);
Exception(const char *, const Exception &);
virtual ~Exception();
const char * message;
const Exception & cause;
};
I should mention that when I leave just implicit constructor and the second one it works.
Thank you for any help.
Your copy constructor is marked explicit, which means it isn't really a copy constructor. Thrown objects must be copyable.
To elaborate:
The explicit
keyword means that a single-argument constructor cannot be used to implicitly convert a variable of the argument type to an object of the constructed type. You have to do it explicitly with the class name. For example, your constructor from const char*
is explicit, so the compiler will never implicitly convert a const char*
to a new object of type Exception
, without you writing out Exception("some string here")
. On the other hand, you do want the compiler to be able to implicitly make one Exception
object into another Exception
object (that's what a copy constructor does!), so by taking the constructor that would otherwise be the copy constructor and marking it with the explicit
keyword, you have completely eliminated its ability to make copies.
By throw Exception();
you create a local instance of the exception class, which is then copied off the stack. Remove explicit
from the copy-constructor.
Edit:
If your copy constructor doesn't do anything - just omit it. The compiler will generate one for you.
精彩评论