【问题标题】:Can you use accessor methods in overloaded operators?您可以在重载运算符中使用访问器方法吗?
【发布时间】:2012-02-09 20:53:13
【问题描述】:

所以我一直被告知,良好的编码实践是使用访问器方法而不是直接访问成员变量,但是在编写重载运算符时,如果在运算符类定义中使用这些访问器方法,我将无法编译。所以假设以下类:

    class Point
    {
    public:
        Point() {};
        virtual ~Point() {};

        // Accessor Methods
        inline void SetX(ushort nX) { m_nX = nX; }
        inline void SetY(ushort nY) { m_nY = nY; }
        inline ushort GetX() { return m_nX; }
        inline ushort GetY() { return m_nY; }

        // Overloaded Operators
        Point operator+(const Point& pnt);

    private:
        ushort m_nX, m_nY;
    };

在运算符定义中,以下内容似乎完全合法,但与我所学的内容背道而驰:

    Point Point::operator+(const Point& pnt)
    {
        Point myPoint;
        myPoint.SetX(GetX() + pnt.m_nX);
        myPoint.SetY(GetY() + pnt.m_nY);
        return myPoint;
    }

但是,以下编译错误:

Point.cpp:7:36: 错误:将 'const Point {aka const Point}' 作为 'ushort Point::GetX()' 的 'this' 参数传递会丢弃限定符 [-fpermissive]

Point.cpp:8:36: 错误:将 'const Point {aka const Point}' 作为 'ushort Point::GetY()' 的 'this' 参数传递会丢弃限定符 [-fpermissive]

    Point Point::operator+(const Point& pnt)
    {
        Point myPoint;
        myPoint.SetX(GetX() + pnt.GetX());    // Here I am trying to use accessor methods vs. member variables
        myPoint.SetY(GetY() + pnt.GetY());
        return myPoint;
    }

如果从参数列表中删除'const'关键字,后面的代码将编译,我不完全理解,只是因为我传入了一个 const 变量,为什么这会消除我使用访问器的能力方法?

【问题讨论】:

  • 您的成员 operator+ 也应该是 const 合格的。您没有修改 this 参数。

标签: c++ methods operators overloading accessor


【解决方案1】:

您的 getter 函数未标记为 const,因此无法在常量对象上调用:

inline ushort GetX() const { return m_nX; }
                     ^^^^^

如果没有const 关键字,编译器必须假定函数可能会修改对象,因此不能在常量对象上调用。还需要注意的是,在某些情况下,您可能需要const 和非const 版本,具有不同的返回类型,例如:

const_iterator vector<T>::begin() const; //const version
iterator vector<T>::begin(); //mutable version

使用 getter 和 setter(在我看来)比直接访问右侧的成员更正确。

【讨论】:

  • +1。我认为关键是 C++ 不知道,除非你告诉它,这些只是 getter,并且在 const 对象上调用它们是安全的。 (这是一件好事;这意味着您不会意外编写调用const 对象上的方法的代码,除非您打算将该方法设为const-安全,而不是,比如说,它只是暂时的const-safe,因为现在它只是一个空存根。)
【解决方案2】:

变化:

inline ushort GetX() { return m_nX; }
inline ushort GetY() { return m_nY; }

到:

inline ushort GetX() const { return m_nX; }
inline ushort GetY() const { return m_nY; }

编译器抱怨试图在 const 对象上调用 non-const 方法。

【讨论】:

    猜你喜欢
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多