在大多数情况下,如果我们重载常量成员函数,则两个重载具有不同的返回类型或参数类型。在大多数情况下,返回类型是不同的。函数通常返回一个成员变量,返回类型是一个引用,其常量不同:
struct IntArray {
int& Get(size_t i); // mutable returns mutable reference
const int& Get(size_t i) const; // const returns const reference
};
但是,是否有一个用例,让两个成员函数具有相同的返回和参数类型(仅在 const 限定方面有所不同)是有意义的?例如:
struct SomeType {
Ret Method(Par1, Par2, Par3);
Ret Method(Par1, Par2, Par3) const;
};
A
non-const
成员函数隐式是一个增变器,但 const
成员函数不是。您可能希望以不同于处理 const
的方式处理 non-const
对象。例如:
struct SomeType {
int Method(int Par1, int Par2, int Par3)
{
this->InternalPar = Par1 + Par2 + Par3;
return this->InternalPar;
};
int Method(int Par1, int Par2, int Par3) const
{
return Par1 + Par2 + Par3;
};
private:
int InternalPar; /* <—- Sync with data persistent storage later */
};
在示例中,
Method
计算其参数的总和并返回该总和。如果它是一个 non-const
对象,它会付出额外的努力来保存此计算的结果。
这可能不是最好的例子,但它是我可以很快想出的即兴例子。