Heitber Andres Montilla Ramirez
unread,May 9, 2020, 8:36:20 PM5/9/20You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
hi everyone I´m learning c++ with a serie of tutorials and I have this error "invalid initialization of non-const reference of type 'Vector3&' from a rvalue of type 'Vector3'
I'd like to know why and how I may solve this issue.
here´s the complete code (the first is the "Vector3.h" file en the other the "main.cpp" file.
#ifndef VECTOR3_H
#define VECTOR3_H
#include <math.h>
class Vector3
{
public:
Vector3(float X = 0.0f, float Y = 0.0f, float Z = 0.0f)
{
x = X;
y = Y;
z = Z;
}
Vector3 operator+=(const Vector3 &vec)
{
return ( *this = (*this + vec) );
}
Vector3 operator+(const Vector3 &vec)
{
return Vector3(vec.x + x, vec.y + y, vec.z +z);
}
//-----------------------------------------------------------
Vector3 operator-=(const Vector3 &vec)
{
return ( *this = (*this - vec) );
}
Vector3 operator-(const Vector3 &vec)
{
return Vector3(x - vec.x, y - vec.y, z - vec.z);
}
//-------------------------------------------------------------
Vector3 operator*=(float num)
{
return ( *this = (*this * num) );
}
Vector3 operator*(float num)
{
return Vector3(x * num, y * num, z * num);
}
//----------------------------------------------------------
Vector3 operator/=(float num)
{
return ( *this = (*this / num) );
}
Vector3 operator/(float num)
{
return Vector3(x / num, y / num, z / num);
}
//---------------------------------------------------------
Vector3 operator-(void)
{
return Vector3(-x, -y, -z);
}
float Dot(Vector3 &vec)
{
return (x * vec.x + y * vec.y + z * vec.z);
}
Vector3 operator*(const Vector3 &vec)
{
return Vector3 (y * vec.z - z * vec.y,
z * vec.x - x * vec.z,
x * vec.y - y * vec.x );
}
float Lenght(void)
{
return sqrt(x * x + y * y + z * z);
}
Vector3 Normalize(void)
{
float lenght = Lenght();
x /= lenght;
y /= lenght;
z /= lenght;
return *this;
}
float Distance(Vector3 &vec)
{
float disX = vec.x - x;
float disY = vec.y - y;
float disZ = vec.z -z;
return sqrt(disX * disX + disY * disY + disZ * disZ);
}
bool operator==(Vector3 &vec)
{
return (vec.x == x && vec.y == y && vec.z == z);
}
bool operator!=(Vector3 &vec)
{
return !(vec == *this);
}
public:
float x, y, z;
};
#endif // VECTOR3_H
-------------------------------------------------------------------------
#include <iostream>
#include "Vector3.h"
using namespace std;
void printVector(Vector3 &vec)
{
cout << vec.x << ", " << vec.y << ", " << vec.z << endl;
}
int main()
{
printVector( Vector3(1, 2, 3) + Vector3(7, 2, 5) );
printVector( Vector3(3, 4, 5) - Vector3(2, 9, 3) );
printVector( Vector3(1, 2, 3) * 5);
cout << Vector3(1, 2, 3).Dot( Vector3(3, 2, 1) ) << endl;
printVector(Vector3(1, 2, 3) * Vector3(4, 5, 6) );
}