[英]Overloading an operator as a member function
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
我看了无数的示例,尝试了我能想到的所有更改,但g ++仍在抱怨
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. 显然,g ++告诉我正在定义成员函数,但尚未将我的运算符声明为成员函数。
Here is the code (I've omitted most of it as it is working fine and is not relevant): vec.h 这是代码(由于工作正常且不相关,因此我省略了大部分代码):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: 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. 抱歉,如果这是重复的内容-我已经搜寻了interwebz几个小时了,但没有发现任何东西。 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. 这是我的Vector2类的一部分,这可能会对您有所帮助。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.