为什么这样做有效?我不明白这种交换的逻辑 [英] Why is this working? I cannot understand the logic of this swapping

查看:77
本文介绍了为什么这样做有效?我不明白这种交换的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

目标是交换两个字符串的第一个元素,但是我创建了一个通用功能,甚至正确。但是,出乎意料的是,我没有使用按引用传递或指针传递!即使这样,当我尝试最终输出a和b时,更改也是永久的!

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?

推荐答案

这几乎可以肯定是由于以下事实:您在代码中的某个位置未显示给我们,您有这行(或类似的内容):

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;

加上此行,则该命名空间std 定义一个函数,如下所示:

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

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

其中 _Ty 模板被替换为 char 在您的 swap(a [0],b [0]); 调用中。

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

添加一个简单的 cout<< 我的掉期<< endl; 行插入您的 交换函数,您会发现它没有被调用。

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

强烈建议阅读:为什么使用命名空间标准?被认为是不好的做法?

这篇关于为什么这样做有效?我不明白这种交换的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆