为什么std::复数实成员函数不是const

Why is std::complex real member function not const?

本文关键字:函数 成员 const std 为什么      更新时间:2023-10-16

std::complex类中的成员函数"real"answers" image "不为const的原因是什么?

complex类模板中real有两个重载:

T real() const;
void real(T);

上的第一个是 const,所以这不是你要问的。

第二个方法,它接受一个T参数,不返回任何东西,不是const,因为它是一个"setter"方法——它的全部意义是改变对象的状态,所以最好不是const

让我们看看c++标准:

c++ 2011第26.4.2节类模板复合物

namespace std {
    template<class T>
    class complex {
        public:
            typedef T value_type;
            complex(const T& re = T(), const T& im = T());
            complex(const complex&);
            template<class X> complex(const complex<X>&);
            T real() const;
            void real(T);
            T imag() const;
            void imag(T);
            complex<T>& operator= (const T&);
            complex<T>& operator+=(const T&);
            complex<T>& operator-=(const T&);
            complex<T>& operator*=(const T&);
            complex<T>& operator/=(const T&);
            complex& operator=(const complex&);
            template<class X> complex<T>& operator= (const complex<X>&);
            template<class X> complex<T>& operator+=(const complex<X>&);
            template<class X> complex<T>& operator-=(const complex<X>&);
            template<class X> complex<T>& operator*=(const complex<X>&);
            template<class X> complex<T>& operator/=(const complex<X>&);
    };
}

我想说的是,std::complex::real()std::complex::imag()都是const方法。