C++ 复制构造函数失败

标签 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;
}

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

据我所知,一切都是正确的,复制构造函数采用 const 引用,因此它应该可以很好地处理所使用的临时变量。

那么错误的原因是什么?

最佳答案

编译器认为test2是一个函数! 了解 most vexing parse .

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

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

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

关于C++ 复制构造函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32572748/

相关文章:

c++ - 如何将基类的私有(private)成员复制到派生类的复制构造函数中

c++ - 在 C++ 中使用 RAII 在线程包装类中 move 语义

c++ - (为什么)用临时/匿名对象实例化模板类是令人讨厌的解析?

c++ - Qt 回调列表

c++ - 使用非空函数对象提升精神语义 Action

c++ - 为什么与 printf 未定义行为中的转换说明符不匹配的参数?

c++ - 从方法堆栈编译中按值返回实例

c++ - QT 中 setter 和 getter 函数的编译器错误

具有构造函数定义但没有实现代码的c++类?

c++ - 如果在 C++ 类中省略复制构造函数,会发生什么(确切地)?