I had a look at the various options suggested as questions that Stackoverflow thought might already have an answer, but nothing I saw came close.
Sample code:
#include <math.h>
class v2
{
public:
float x;
float y;
v2(float angle) : x(cos(angle)), y(sin(angle)) {}
v2(const v2 &v) : x(v.x), y(v.y) {}
};
int main(int argc, char **argv)
{
float const angle(1.0f);
v2 const test1(angle);
v2 const test2(v2(angle));
v2 const test3(test1);
float const x1(test1.x);
float const y1(test1.y);
float const x2(test2.x); // These two lines fail, claiming left of .x must have class type.
float const y2(test2.y);
float const x3(test3.x);
float const y3(test3.y);
return 0;
}
This is with MSVC, from VS 2010. The creation of test2 compiles correctly, but access of its members fails, claiming test2 does not have a class type.
As far as I can see everything is correct, the copy constructor takes a const reference, so it should work just fine with the temporary being used.
So what is the cause of the error?
The compiler thinks that test2 is a function! Read about the most vexing parse.
You can resolve this with either of these two :
v2 const test2((v2(angle))); // before C++11
v2 const test2{v2(angle)}; // C++11 uniform initialization
You have fallen victim to the most vexing parse. In your code, you've declared test2
as a function. One way to fix this is to add an extra set of parenthesis: v2 const test2((v2(angle)));
.
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