简体   繁体   中英

How does the compiler decide which function to call?

supposed there are two overloaded member function(a const version and a non-const version) in the String class:

char & String::operator[](int i)         //Version 1
{
    cout<<"char & String::operator[](int i) get invoked."<<std::endl;
    return str[i];
}


const char & String::operator[](int i) const       //Version 2
{

    cout<<"const char & String::operator[](int i) const get invoked."<<std::endl;
    return str[i];
}

and there is a test code fragment

int main(){
    String a;
    cout<<a[0]<<endl;  //Line 1
    a[0]='A';     //Line 2
}

How does the compiler decide which function to call? I found that Version 1 always got called when I run the program. Could anybody tell me why it is? And how can Version 2 got called?

If a is const, the second overload will get called.

int main(){
    const String a;
    cout<<a[0]<<endl;   // would call const version
    a[0]='A';           // will not compile anymore
}

If the object is const , the the const member function will be called. If the object is non-const the non-const member-function is called.

Exception
If their is only the const function, it is called in any case.

#include <iostream>
using namespace std;

class Foo {
public:
    void print() {
        cout << "Foo non-const member function\n";
    }
    void print() const {
        cout << "Foo const member function\n";
    }
};

class Bar {
public:
        void print() const {
                cout << "Bar const member function\n";
        }
};


int main() {
    Foo foo_non_const;
    const Foo foo_const;

    Bar bar_non_const;
    const Bar bar_const;

    foo_non_const.print();
    foo_const.print();

    bar_non_const.print();
    bar_const.print();

    return 0;
}

$ ./blah

Foo non-const member function
Foo const member function
Bar const member function
Bar const member function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM