sorry for the question title but I didn't know a correct title for my problem. I have the following code example:
struct test {
test(int a) {
}
};
int main() {
test(1);
return 0;
}
The above example code works. Now i do (in my understanding) the same a bit differently:
struct test {
test(int a) {
}
};
int main() {
int a = 0;
test(a);
return 0;
}
When I compile this I get the following error:
error: redefinition of 'a' with a different type: 'test' vs 'int'
But in my opinion it gets really strange when I try this:
struct test {
test(int a) {
}
};
int main() {
int a = 0;
test((int)a);
return 0;
}
the above example works again and really confuses me since I don't see the difference (except casting an int to an int). Can anyone explain what's going on? Thank you in advance.
You forgot to give your test
variable a name, causing test(a);
to be a declaration of a variable named a
of type test
.
In the other cases, since test(1)
and test((int)a)
cannot be declarations, but must be some kind of call, your compiler will treat that as constructing a temporary object of type test
without a name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With