請明確解釋在以下情況下方法解析規則爲。我有一個想法,基於代碼的行爲,但想澄清。我的方法調用如何解決?
基於「調用對象的常量性決定了哪個版本MYARRAY的::獲取()將被調用,因此不論是否來電給出與他就可以操縱或僅觀察到的私人數據的引用這兩個方法在技術上有不同的簽名,因爲它們的「this」指針有不同的類型,允許編譯器從wikipedia const correctness中選擇合適的「,我會得出結論,我的例子應該是方法重載的情況,而不是方法覆蓋(因爲const方法和非const方法有兩個不同的簽名)。
class Base
{
public:
void test()
{ std::cout << "nonconst call" << std::endl; }
};
class Child : public Base
{
public:
void test() const
{
std::cout << "const call" << std::endl;
Child * nonConstThis = const_cast<Child * >(this);
Base * nonConstBase = dynamic_cast<Base * >(nonConstThis);
// This call leads to infinite recursion by calling
// "void Child::test() const", which implies that
// a "Child *" will resolve to calling a const Child function
// before calling a non-const Base function.
//nonConstThis->test();
// This will call "void Base::test()"
nonConstBase->test();
}
};
void main()
{
Child * child = new Child;
child->test();
}
對。 'Child'中的const版本隱藏'Base'中的非const版本,並防止它成爲重載。 – 2012-03-12 20:35:39