Why is this working? I cannot understand the logic of this swapping

主宰稳场 提交于 2020-05-16 03:22:17

问题


int main() {
    // Complete the program
    string a,b;
    getline(cin,a);
    getline(cin,b);
    cout<<a.size()<<" ";
    cout<<b.size();
    string c=a+b;
    cout<<endl<<c;

    swap(a[0],b[0]);
    cout<<endl<<a<<" "<<b;
    return 0;
}
void swap(string s1,string s2){
    string temp=s1;
    s1=s2;
    s2=temp;
}

Well the target is to swap the first element of both strings, but I created a general function for that and even got it right. But, unexpectedly, I didn't use pass by reference or pointer! Even then, the changes are permanent when I try to output a and b in the end!

Logically it shouldn't work but it is working. Is it something to do with the strings?


回答1:


This is almost certainly due to the fact that, somewhere in code that you have not shown us, you have this line (or something very similar):

using namespace std;

With this line included, then that very namespace std defines a function as follows:

void swap(_Ty& _Left, _Ty& _Right);

Where the _Ty template is replaced with char in your swap(a[0],b[0]); call.

Add a simple cout << "My Swap" << endl; line to your swap function, and you'll see it's not being called.

Highly recommended reading: Why is "using namespace std;" considered bad practice?.



来源:https://stackoverflow.com/questions/61564027/why-is-this-working-i-cannot-understand-the-logic-of-this-swapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!