[英]Overloading an operator as a member function
我正在研究向量類,並試圖重載一些運算符。 我看了無數的示例,嘗試了我能想到的所有更改,但g ++仍在抱怨
include/vector.cpp:9:38: error: no ‘vec vec::operator+(const vec&)’ member function declared in class ‘vec’
顯然,g ++告訴我正在定義成員函數,但尚未將我的運算符聲明為成員函數。
這是代碼(由於工作正常且不相關,因此我省略了大部分代碼):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;
}
抱歉,如果這是重復的內容-我已經搜尋了interwebz幾個小時了,但沒有發現任何東西。 當我看到我的錯誤很明顯時,我肯定會感到尷尬:)謝謝
這是我的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.