我的结果有问题。实际上,我创建了一个Vector类,然后重新定义了运算符。但是,运营商" - "给我两个不同的结果进行相同的操作。当我打印操作时,它给了我很好的答案,但是当我想将结果存入变量时,结果是不同的。
我是否想念班上的操作员?
我的主要是:
#include "../include/Vecteur.hpp"
int main(){
vec3f v0(1.0f, 1.0f, 1.0f);
vec3f v1(1.0f, 0.0f, 0.0f);
v1.x() += 3.0f;
v0[1] -= 1.0f;
cout << "v0 = " << v0 << endl;
cout << "v1 = " << v1 << endl;
float l = v0.length();
v1 *= l;
cout << "l = " << l << endl;
cout << "v0 = " << v0 << endl;
cout << "v1 = " << v1 << endl;
auto v2 = v0 + v1;
cout << "v2 = " << v2 << endl;
auto v3 = v0 - v1; // The problem is there.
cout << "v0 = " << v0 << endl;
cout << "v1 = " << v1 << endl;
cout << "v3 = " << v3 << endl; // Prints [1,0,1] instead of [-4.65685, 0, 1]
cout << v0-v1 << endl; // Prints [-4.65685, 0, 1]
if (v2 < v3){
v2 += v3;
}
cout << "v2 = " << v2 << endl;
return 0;
}
有我的班级:
#include <iostream>
#include <math.h>
using namespace std;
class vec3f{
private:
float tableau[3];
public:
vec3f(){}
vec3f(float f1, float f2, float f3){
this->tableau[0] = f1;
this->tableau[1] = f2;
this->tableau[2] = f3;
}
float x() const{
return this->tableau[0];
}
float y() const{
return this->tableau[1];
}
float z() const{
return this->tableau[2];
}
float & x(){
return this->tableau[0];
}
float & y(){
return this->tableau[1];
}
float & z(){
return this->tableau[2];
}
float length() const{
return sqrt(( pow(this->tableau[0],2) + pow(this->tableau[1],2) + pow(this->tableau[2],2) ));
}
/* Redifinition of operators */
vec3f operator+(vec3f const & v){
this->tableau[0] += v.x();
this->tableau[1] += v.y();
this->tableau[2] += v.z();
return *this;
}
vec3f operator-(vec3f const & v){
this->tableau[0] -= v.x();
this->tableau[1] -= v.y();
this->tableau[2] -= v.z();
return *this;
}
vec3f operator*=(float const & f){
this->tableau[0] *= f;
this->tableau[1] *= f;
this->tableau[2] *= f;
return *this;
}
bool operator<(vec3f const & v){
return (this->tableau[0]<v.x() && this->tableau[1]<v.y() && this->tableau[2]<v.z());
}
vec3f & operator=(vec3f const & v){
return *this;
}
vec3f operator=(vec3f const & v) const{
return *this;
}
float operator[](size_t i) const{
return tableau[i];
}
float & operator[](size_t i){
return tableau[i];
}
};
ostream & operator<<(ostream & out, vec3f const & v){
out << "[" << v.x() << ", " << v.y() << ", " << v.z() << "]";
return out;
}
vec3f operator+(vec3f const & va, vec3f const & vb){
return vec3f(va.x()+vb.x(),va.y()+vb.y(),va.z()+vb.z());
}
vec3f operator-(vec3f const & va, vec3f const & vb){
return vec3f(va.x()-vb.x(),va.y()-vb.y(),va.z()-vb.z());
}
vec3f operator+=(vec3f const & va, vec3f const & vb){
return vec3f(va.x()+vb.x(),va.y()+vb.y(),va.z()+vb.z());
}
谢谢:)
答案 0 :(得分:2)
在课程中,您可能希望定义运算符+=
和-=
(就像您为*=
所做的那样)。但您忘了=
- 并将+
,-
定义为修改操作数的成员函数。