C ++ copy constructor crash

I looked at the various options suggested as questions that Stackoverflow thought might already have an answer, but nothing I saw came close.

Code example:

#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 since VS 2010. Creating test2 compiles correctly, but its members' access fails, claiming that test2 does not have a class type.

As far as I can see, everything is correct, the copy constructor accepts a reference to a constant, so it should work fine with temporary use.

So what is the cause of the error?

+4
source share
2 answers

, test2 - ! .

:

v2 const test2((v2(angle)));  // before C++11

v2 const test2{v2(angle)};    // C++11 uniform initialization
+11

. test2 . - : v2 const test2((v2(angle)));.

+9

Source: https://habr.com/ru/post/1607336/


All Articles