【问题标题】:Overloading an operator as a member function将运算符重载为成员函数
【发布时间】:2023-12-28 02:04:01
【问题描述】:

我正在研究一个矢量类,并试图重载一些运算符。我看过无数的例子,尝试了我能想到的每一个改动,但 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 上搜索了几个小时,但没有找到任何东西。当我看到我的错误如此明显时,我相信我会感到尴尬:) 谢谢

【问题讨论】:

  • 您的代码看起来正确,您实现了getx()gety() 函数吗?它们似乎没有声明/定义。你确定这是你唯一的错误吗?我成功编译了你的代码,ideone.com/FZPkRH
  • 这段代码是正确的。它真的是你拥有的那个吗?也许您声明了运算符const(这实际上是有道理的)但定义不是const
  • 这是复制和粘贴的——我几乎去掉了其他所有内容。 getx(), gety() 工作正常 - 我整天都在使用它们。
  • @BenKushigian 2 件事要尝试:1. 用 vector.h 以外的名称命名您的标题。即使您使用#include "vector.h",有时编译器最终还是会包含标准库中的内容,并且您可能会遇到某种文件/名称冲突。 2. 将operator+ 标记为const,因为它没有修改任何成员。 vec operator+( const vec&amp; other) const; 我不认为这是你的错误的根源,但这可能有助于至少避免未来的错误。

标签: c++ operator-overloading member-functions


【解决方案1】:

这是我的 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;
}

【讨论】: