I'm working on a vector class and am trying to overload some operators. I've looked at countless examples, tried every alteration I can think of, and still g++ is complaining
include/vector.cpp:9:38: error: no ‘vec vec::operator+(const vec&)’ member function declared in class ‘vec’
Obviously g++ is telling me that I'm defining a member function but that I haven't declared my operator as a member function.
Here is the code (I've omitted most of it as it is working fine and is not relevant): vec.h
#ifndef _BEN_VECTOR
#define _BEN_VECTOR
#include <math.h>
#include <string>
#include <sstream>
class vec{
public:
/* Constructor */
vec(double X, double Y);
/* OPERATORS */
vec operator+( const vec& other);
private:
int dims;
double x;
double y;
};
#endif /* _BEN_VECTOR */
vec.cpp:
#include "vector.h"
/* CONSTRUCTORS */
vec::vec(double X, double Y){
x = X; y = Y; dims = 2;
}
/* OPERATORS */
vec vec::operator+( const vec& other ){
vec v(this->gety() + other->getx(), this->gety() + other->gety());
return v;
}
Sorry if this is a duplicate -- I've been scouring the interwebz for hours now and haven't found anything. I'm sure I'll be embarrassed when I see how obvious my mistake is :) Thanks
Here is part of my Vector2 class maybe this will help you.
class Vector2 {
public:
union {
float m_f2[2];
struct {
float m_fX;
float m_fY;
};
};
inline Vector2();
inline Vector2( float x, float y );
inline Vector2( float* pfv );
// ~Vector2(); // Default Okay
// Operators
inline Vector2 operator+() const;
inline Vector2 operator+( const Vector2 &v2 ) const;
inline Vector2& operator+=( const Vector2 &v2 );
};
inline Vector2::Vector2() :
m_fX( 0.0f ),
m_fY( 0.0f ) {
}
inline Vector2::Vector2( float x, float y ) :
m_fX( x ),
m_fY( y ) {
}
inline Vector2::Vector2( float* pfv ) :
m_fX( pfv[0] ),
m_fY( pfv[1] ) {
}
// operator+() - Unary
inline Vector2 Vector2::operator+() const {
return *this;
}
// operator+() - Binary
inline Vector2 Vector2::operator+( const Vector2 &v2 ) {
return Vector2( m_fX + v2.m_fX, m_fY + v2.m_fY );
}
// Operator+=()
inline Vector2& Vector2::operator+=( const Vector2 &v2 ) {
m_fX += v2.m_fX;
m_fY += v2.m_fY;
return *this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.