[英]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.