问题
I have a problem with a default constructor in C++. It's a simple thing but can't see what's wrong with it.
I have a constructor with 3 optional parameters, with const values on initialization list:
data::data(int D = 1, int M = 1, int Y = 1583) : Day(D), Month(M), Year(Y)
{
if (!CorrectDate()) throw "Wrong Date!";
}
Why can I call it with one, two or three parameters and it works just fine but doesn't when I call it with no parameters?
data tommorrow();
回答1:
data tomorrow(); is a declaration of a function that returns a data and takes no parameters. To create a data object with no explicit constructor arguments, just do data tomorrow; without the parentheses.
回答2:
Define it as
data tomorrow;
data tomorrow(); is the same as defining a function called tomorrow which returns data
回答3:
You are probably doing something like
data something();
which is not an initialization of a variable of type data called something, but the declaration of a function called something that returns data.
If this is the case, the correct would be:
data something;
回答4:
You are declaring a function which returns a data, you can do either:
data tommorow;
Without (), or you can do:
data tommorow = data();
来源:https://stackoverflow.com/questions/5385675/calling-default-constructor