【发布时间】:2021-01-20 13:54:06
【问题描述】:
using namespace std;
template <typename A>
class vector3d_add
{
public:
vector3d_add(A x, A y, A z);
virtual ~vector3d_add();
void setX(A x);
void setY(A y);
void setZ(A z);
void display();
A getX();
A getY();
A getZ();
A operator+ (const A& v2);
A& operator+= (const A& v2);
private:
A x;
A y;
A z;
};
template <typename A>
vector3d_add<A>::~vector3d_add()
{
cout << "deleted" << endl;
}
template <typename A>
vector3d_add<A>::vector3d_add(A x, A y, A z)
{
this->x = x;
this->y = y;
this->z = z;
}
template <typename A>
A& operator+=(const A& v2) //x1
{
this->x += v2.x;
this->y += v2.y;
this->z += v2.z;
return *this;
}
template <typename A>
A operator+(const A& v2)
{
return A(*this) += v2; //x2
}
template <typename A>
void vector3d_add<A>::display()
{
cout<<this->x<<endl<<this->y<<endl<<this->z<<endl;
}
int main()
{
VECTOR<int>v1(10,10,10);
VECTOR<int>v2(10,10,10);
VECTOR<int>v3=v2+v1;
v3.display();
}
我想实现一个代码,它可以添加带有模板和运算符重载的 3D 向量(必须使用 +operator 和 +=operator)。 我不知道如何进一步。
我在互联网上搜索了其他解决方案,但 nodody 使用的是 + 运算符和 += 运算符。
我尝试了其他的方法来实现它,但我不明白。
错误:
x1->'A& operator+=(const A&)' 必须正好有两个参数
x2->在非成员函数中无效使用'this'
【问题讨论】:
-
我在互联网上搜索了其他解决方案,但 nodody 正在使用 +operator 和 +=operator。 -- 你真的搜索得不够努力,因为几乎所有使用
+的编写良好的代码都同时重载了+和+=。提示——首先写operator +=,而不是operator +。然后从那里开始工作。 -
感谢您的快速回答,但我真的不知道如何对 += 运算符进行编程,如果可行的话,我需要有人可以检查我的代码。
-
I need someone who can check my code, if it would work.和// Dontknow how to do this overloading不要解释你的问题是什么。构建时是否收到错误消息?您在// Dontknow how to do this overloading尝试过什么? -
我很确定
glm、Eigen和其他的 vec3 实现都使用`+=operator`和+operator。 -
还有这个问题What are the basic rules and idioms for operator overloading? 和这个answer 的二元算术运算符 部分带有
operator +和operator +=的示例。
标签: c++ templates vector 3d operator-overloading