需要在函数声明中使用 const 关键字

问题描述 投票:0回答:0

我遇到了一个错误,我没有真正理解就解决了。
我有一个实现固定点的类

Fixed
,和一个实现二维简单点的类
Point

#include <ostream>

class Fixed
{
    public:
        Fixed();
        Fixed( Fixed& a );
        Fixed( const Fixed& a );
        Fixed( const int n );
        Fixed( const float f );
        ~Fixed();

        int     getRawBits() const;
        void    setRawBits( int const raw );
        int     toInt() const;
        float   toFloat() const;

        Fixed& operator=( const Fixed& a );

// Prototype that did not work with Point's << operator
        // friend std::ostream& operator<<( std::ostream& os, Fixed& r) ;
// Prototype that works with Point's << operator
        friend std::ostream& operator<<( std::ostream& os, const Fixed& r) ;

        bool operator>( const Fixed& r ) const;
        bool operator<( const Fixed& r ) const;
        bool operator>=( const Fixed& r ) const;
        bool operator<=( const Fixed& r ) const;
        bool operator==( const Fixed& r ) const;
        bool operator!=( const Fixed& r ) const;
        Fixed operator+(const Fixed& r ) const;
        Fixed operator-(const Fixed& r ) const;
        Fixed operator*(const Fixed& r ) const;
        Fixed operator/(const Fixed& r ) const;
        Fixed& operator++();
        Fixed operator++( int n );
        Fixed& operator--();
        Fixed operator--( int n );
        static       Fixed& min( Fixed& a, Fixed& b );
        static const Fixed& min( const Fixed& a, const Fixed& b );
        static       Fixed& max( Fixed& a, Fixed& b );
        static const Fixed& max( const Fixed& a, const Fixed& b );

    private:
        int _value;
        static const int    _binaryPoint = 8;
};

#include "Fixed.hpp"
#include <ostream>

class Point
{
    public:
        Point();
        Point( Point &p );
        Point( const Point &p );
        Point( const float x, const float y );
        ~Point();

        Point& operator=( const Point& l );
        friend std::ostream& operator<<( std::ostream& os, Point& r );

    private:
        const Fixed _x;
        const Fixed _y;
};

我的问题发生在我的

<<
类的
Point
重载运算符中。这是:

std::ostream& operator<<( std::ostream& os, Point& r )
{
    os << "(" << r._x << "," << r._y << ")";
    return os;
}

问题出在

Point
的私人成员
_x
_y
const Fixed
。然后它试图调用
Fixed
<<
重载运算符,但是因为它被声明接受
Fixed&
参数而不是
const Fixed&
,所以它没有编译。

所以我确定了错误,但想知道可能相关的两件事:

  1. 为什么编译器需要
    const
    说明符?
  2. 我是否应该在我的
    const
    类中取消注释没有
    Fixed
    的原型(并且显然在我的
    .cpp
    中添加代码),以拥有 2 个原型并在任何情况下“安全”(?)?
c++ constants operator-overloading
© www.soinside.com 2019 - 2024. All rights reserved.