C++中模板类中的'const'方法

JMz*_*nce 0 c++ templates const object

我刚刚开始阅读C++中的模板类,我遇到了一些我不知道的语法.类方法的原型如下:

template <class Type> class Range {
            ....
        bool Below    (const Type& value) const;
            ....
}
Run Code Online (Sandbox Code Playgroud)

并定义为:

template <class Type> bool Range<Type>::Below(const Type& Value) const {

    if (Value < Lo) return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

在列出方法输入后,任何人都可以帮助我理解'const'标志的含义吗?我明白在输入之前使用时有用,但之后没有.干杯,杰克

Max*_*kin 8

const成员函数中,顶级 const限定符应用于类的每个成员,除非成员被标记为mutable(这意味着从不const).

您还可以拥有volatile成员函数以及volatileconst.

注意,对于指针和引用,行为可能会令人惊讶:

struct X {
    int a;
    int* pa;
    int& ra;
    X() 
        : a(1)
        , pa(&a) 
        , ra(a)
    {}

    void foo() const {
        *pa = 2; // Ok, this is the pointer being const, not the value being pointed to.
        ra = 3; // Ok, this is the reference being const, not the value being referenced.
        a = 4; // Error, a is const
        pa = &a; // Error, pa is const.
    }
};
Run Code Online (Sandbox Code Playgroud)

以下是顶级 const限定符的应用方式:

  • int变成int const- 一个常数整数.
  • int*变成int* const- 一个常量指针,而不是int const*- 指向常量的指针.
  • int&变成int& const- 一个常量引用,而不是int const&- 对常量的引用.应用于const引用不会执行任何操作,因为无论如何它们都无法更改为引用另一个对象.

另一种思考方式是,在非const成员函数中this具有类型X* const,而在const成员函数中this则是X const* const.注意this 指针总是如何不变.