C++ Calling methods with same signature but different scope

This question already has an answer here:

  • Meaning of “const” last in a C++ method declaration? 7 answers

  • Functions can be overloaded based on their const ness alone. This is an important feature of C++.

    // const member function:
    const XMLAttribute* FindAttribute( const char* name ) const;
    
    // non-const member function
    XMLAttribute* FindAttribute( const char* name );
    

    In this case, the const that makes the functions different is the const following the parentheses. The const before the parenthesis does not belong to the method signature whilst the const that follows the parenthesis does. This latter use of const specifies which member functions may be called from const objects and which may not. In other words, it specifies the contract for const objects.

    If you have a const object, the const method will be called:

    const MyObject cObj;
    cObj.FindAttribute("cats");
    // const method will be called
    

    If you have a non- const object, the compiler will look for a non- const method and call it. If it does not exist, it will look for a const method and call that. The compiler works this way because it is legal to call const member functions from non- const objects, but it is illegal to call non- const member functions from const objects.

    MyObject obj;
    obj.FindAttribute("cats");
    // non-const method will be called
    // if it does not exist the compiler will look for a const version
    

    I am a bit confused how as to how a method can have the same signature in both public and private scopes.

    They don't have the same signature actually

    const XMLAttribute* FindAttribute( const char* name ) const;
                                                       // ^^^^^^
    

    the public method is applicable for const access to the containing class. This counts for the function signature uniqueness.

    链接地址: http://www.djcxy.com/p/40426.html

    上一篇: const T&value()const是什么意思?

    下一篇: C ++调用具有相同签名但范围不同的方法