C++拷贝构造函数失败

dgn*_*uff 4 c++ copy-constructor most-vexing-parse

我看了一下Stackoverflow认为可能已经有答案的问题所提出的各种选项,但我看到的并没有结束.

示例代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是来自VS 2010的MSVC.test2的创建正确编译,但其成员的访问失败,声称test2没有类类型.

据我所知,一切都是正确的,复制构造函数采用const引用,因此它应该可以正常使用临时工具.

那么错误的原因是什么?

Man*_*dis 11

编译器认为test2是一个函数!阅读最令人烦恼的解析.

您可以使用以下两种方法解决此问题:

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

v2 const test2{v2(angle)};    // C++11 uniform initialization
Run Code Online (Sandbox Code Playgroud)


Moo*_*oys 10

你已成为最令人烦恼的解析的牺牲品.在您的代码中,您已声明test2为函数.解决这个问题的一种方法是添加一组额外的括号:v2 const test2((v2(angle)));.