复制构造函数调用无限循环

Ily*_*ski 2 c++ infinite-loop copy-constructor

我传递一个值来复制构造函数作为引用,但是正在调用一个无限循环.

这是我的班级:

class Vector2f{
private:
    GLfloat x;
    GLfloat y;

public:
    Vector2f();
    Vector2f(const GLfloat _x, const GLfloat _y);
    Vector2f(const Vector2f &_vector);

    ~Vector2f();
};
Run Code Online (Sandbox Code Playgroud)

这是方法的实现:

Vector2f::Vector2f():
        x( 0.0f ),
        y( 0.0f )
{
    DebugLog("Vector2f constructor");
}

Vector2f::Vector2f(const GLfloat _x, const GLfloat _y):
        x( _x ),
        y( _y )
{
    DebugLog("Vector2f constructor(%f, %f)", _x, _y);
}


Vector2f::Vector2f(const Vector2f &_vector):
        x( _vector.getX() ),
        y( _vector.getY() )
{
    DebugLog("Vector2f copy constructor");
}

Vector2f::~Vector2f()
{

}
Run Code Online (Sandbox Code Playgroud)

以下是我访问该类的方法:

Vector2f tempVector1 = Vector2f(0.0f, 0.0f);
DebugLog("tempVector1 initialized");

Vector2f tempVector2;
tempVector2 = Vector2f(0.0f, 0.0f);
DebugLog("tempVector2 initialized");
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

Vector2f constructor(0.000000, 0.000000)
tempVector1 initialized
Vector2f constructor
Vector2f constructor(0.000000, 0.000000)
Vector2f copy constructor
Vector2f copy constructor
Vector2f copy constructor
...
Run Code Online (Sandbox Code Playgroud)

尝试初始化以前创建的对象时发生无限循环.如果我尝试将tempVector1复制到tempVector 2中,也会发生无限循环:

Vector2f tempVector2;
tempVector2 = Vector2f(tempVector1);
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,如何防止它进入无限循环?

先感谢您.

R S*_*hko 6

这一行:

tempVector2 = Vector2f(tempVector1);
Run Code Online (Sandbox Code Playgroud)

会调用operator =,而不是复制构造函数.你是在定义一个运算符=做一些古怪的事吗?

另外,你的代码在Linux上使用g ++ 4.3.2和在Mac上使用g ++ 4.2.1(在我定义了getX,getY,将DebugLog转换为printf并使用float而不是GLfloat之后).

  • 我也会说同样的,有些代码不可见.从上面显示的代码,我看不出任何问题. (2认同)