C ++ Xcode没有用于初始化vector2d类型的匹配构造函数

时间:2016-04-22 16:55:44

标签: c++ xcode

我有一个vector2d类。我在以下代码中收到错误“初始化类型没有匹配的构造函数”:

vector2d vector2d::operator+(const vector2d& vector)
{
   return vector2d((this->x + vector.x), (this->y + vector.y));
}

vector2d vector2d::operator-(const vector2d& vector)
{
   return vector2d(this->x - vector.x, this->y - vector.y);
}

我的向量类声明和定义是:

#ifndef __VECTOR2D_H__
#define __VECTOR2D_H__

class vector2d
{
public:
    float x, y , w;

    vector2d(const float x, const float y) ;
    vector2d(vector2d& v) ;

    vector2d operator+(const vector2d& rhs);
    vector2d operator-(const vector2d& rhs);

    vector2d& operator+=(const vector2d& rhs);
    vector2d& operator-=(const vector2d& rhs);

    float operator*(const vector2d& rhs);

    float crossProduct(const vector2d& vec);

    vector2d normalize();

    float magnitude();
};

#endif

vector2d.cpp:

#include "vector2d.h"
#include <cmath>

vector2d::vector2d(const float x,const float y) :x(x),y(y),w(1)
{

}

vector2d::vector2d(vector2d& vector) : x(vector.x), y(vector.y), w(1)
{

}

vector2d vector2d::operator+(const vector2d& vector)
{
  return vector2d((this->x + vector.x), (this->y + vector.y));
}

vector2d vector2d::operator-(const vector2d& vector)
{
  return vector2d(this->x - vector.x, this->y - vector.y);
}

vector2d& vector2d::operator+=(const vector2d& vector)
{
 this->x += vector.x;
 this->y += vector.y;

 return *this;
}

vector2d& vector2d::operator-=(const vector2d& vector)
{
 this->x -= vector.x;
 this->y -= vector.y;

 return *this;
}

float vector2d::magnitude()
{
 return sqrt(this->x * this->x + this->y * this->y);
}

//Make Unit Vector
vector2d vector2d::normalize()
{
 float magnitude = this->magnitude();

 float nx = 0.0f;
 float ny = 0.0f;

 nx = this->x / magnitude;
 ny = this->y / magnitude;

 return vector2d(nx,ny);
}

float vector2d::operator*(const vector2d& rhs)
{
 return ( (this->x * rhs.x) + (this->y * rhs.y) );
}

float vector2d::crossProduct(const vector2d& vec)
{
  return (x * vec.y - y * vec.x);
}

我没有使用默认构造函数参数创建对象,那么该错误的原因是什么?请注意,代码在Visual Studio上运行完全正常。在Xcode上我得到了错误。

1 个答案:

答案 0 :(得分:1)

你的问题将是这个构造函数:

vector2d(vector2d& v) ;

标准的复制构造函数如下所示:

vector2d(const vector2d& v) ;

因为在标准c ++中你不能将临时绑定到可变的左值引用

不幸的是,微软凭借他们的智慧释放了许多扩展&#34; (即,与标准的恶意偏差)进入他们的编译器和仅在MSVC中,临时将绑定到可变的l值引用。

real 标准c ++中,临时可以绑定到:

  1. 副本vector2d(vector2d v) ;
  2. 一个const lvalue-reference vector2d(const vector2d& v) ;
  3. rvalue-reference vector2d(vector2d&& v) ;
  4. `