[英]How does overloading of const and non-const functions work?
STL
中充满了这样的定义:
iterator begin ();
const_iterator begin () const;
由于返回值不参与重载解析,这里唯一的区别是函数是const
。 这是重载机制的一部分吗? 解析一行的编译器算法是什么:
vector<int>::const_iterator it = myvector.begin();
编译器的“算法”是这样的:类 X 的每个成员函数都有一个类型为 X& 的隐式参数(我知道,大多数人认为它是 X*,但标准规定,为了重载解析的目的,我们假设它是一个引用)。 对于 const 函数,参数的类型是 const X&。 因此,如果一个成员函数被调用,那么算法,const 和 non-const 两个版本都是可行的候选者,并且就像在其他重载解析情况下一样选择最佳匹配。 没有魔法:)
在你给出的例子中:
vector<int>::const_iterator it = myvector.begin();
如果myvector
不是 const,则将调用begin()
的非常量版本,并且您将依赖从迭代器到 const_iterator 的隐式转换。
是的, const
修饰符会影响重载。 如果myvector
是const
,则将调用const
版本:
void stuff( const vector<int>& myvector )
{
vector<int>::const_iterator it = myvector.begin(); //const version will be called
}
vector<int> myvector;
vector<int>::const_iterator it = myvector.begin(); //non-const version will be called
来自 C++ 标准(第 13.3.1 节候选函数和参数列表):
For non-static member functions, the type of the implicit object parameter is “reference to cv X” where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. [Example: for a const member function of class X, the extra parameter is assumed to have type “reference to const X”. ]
因此,在您的情况下,如果myvector
对象是const
编译器将选择begin
版本,该版本具有reference to const vector
类型reference to const vector
隐式对象参数,这是begin
const 版本。
值得一提的是,c++允许 const 方法/函数重载(例如 foo() const),但不允许 const 参数重载(例如 bar(int a) 和 bar(const int a))。
编译器在编译时确定对象变量是否为 const
然后它选择相应的重载,以及它具有的任何返回类型。
class C {
public:
int f() { return 1; }
float f() const { return 1.5; }
};
// Non const.
C c;
assert(c.f() == 1);
// Convert variable const at compile time.
assert(const_cast<const C&>(c).f() == 1.5);
// Same as above but with an explicit reference.
const C& d = c;
assert(d.f() == 1.5);
// Analogous but with a new const object from the start.
const C e;
assert(d.f() == 1.5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.