目前,我正在开发一个CVector课程,一切正常,直到我想在CVector v;
等其他课程中使用矢量并稍后使用v
。
struct Vector3_t {
float x, y , z;
};
但是我想对这些向量使用运算符,所以我做了一个类:
class CVector
{
public:
//missing usage: CVector vec; // for later usage in example.
CVector() // usage: CVector v();
{
this->x = 0, this->y = 0, this->z = 0;
}
CVector(const float x = 0, const float y = 0) { // usage: CVector v(1,2); // but z is always 0
this->x = x, this->y = y,this->z = 0;
}
CVector(const float x = 0, const float y = 0, const float z = 0) { // usage: CVector v(1,2,3);
this->x = x, this->y = y, this->z = z;
}
CVector & CVector::operator += (const CVector & v) {
this->x += v.x; this->y += v.y; this->z += v.z; return *this;
}
const CVector CVector::operator + (const CVector& v) const {
CVector r(*this); return r += v;
}
float x, y, z;
~CVector() {};
protected:
private:
};
行动中:
int main() {
CVector vec;
return 0;
}
输出错误: 严重级代码描述项目文件行抑制状态 错误(活动)类" CVector"有多个默认构造函数mebad c:\ Users \ lifesucks \ Documents \ Visual Studio 2015 \ Projects \ mebad \ mebad \ main.cpp 43
*严重级代码描述项目文件行抑制状态
错误C2668' CVector :: CVector':模糊调用重载函数mebad c:\ users \ lifesucks \ documents \ visual studio 2015 \ projects \ mebad \ mebad \ main.cpp 43
*
基本上我只是不知道如何在有多个构造函数的情况下为这种用法声明类,并且我不想使用更多函数,如CVector :: constr1,这将使用3个浮点数或任何类似的东西,必须有一种方法这样做,我能得到一点帮助吗?谢谢!
答案 0 :(得分:3)
问题是你对两个构造函数的参数使用默认值,这意味着你有三个可以不带参数调用的构造函数,那么编译器应该调用哪个?
只需删除默认参数值即可。
答案 1 :(得分:0)
你的课应该是
class CVector
{
public:
CVector() : x(0), y(0), z(0) {}
CVector(float x) : x(x), y(0), z(0) {}
CVector(float x, float y) : x(x), y(y), z(0) {}
CVector(float x, float y, float z) : x(x), y(y), z(z) {}
//...
float x, y, z;
};
或
class CVector
{
public:
CVector(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {}
//...
float x, y, z;
};
答案 2 :(得分:0)
Joachim Pileborg完美地回答了这个问题,值得一提。
以下是您可以进行的代码更改:
CVector() // usage: CVector v();
{
this->x = 0, this->y = 0, this->z = 0;
}
CVector(const float x, const float y) { // usage: CVector v(1,2); // but z is always 0
this->x = x, this->y = y,this->z = 0;
}
CVector(const float x, const float y, const float z) { // usage: CVector v(1,2,3);
this->x = x, this->y = y, this->z = z;
}