使用用户函数在 C++ 中交换两个结构

swap two structures in c++ using a user function

本文关键字:结构 两个 交换 用户 函数 C++      更新时间:2023-10-16

我有以下代码对我来说看起来不错我的目的是交换两个结构的名称和 CNE 的但是"echange"功能看起来什么都不像做任何事情这是我写的代码:

    #include <iostream>
using namespace std;
struct etudiant{
    char* nom ;
    int cne ;
};
void echanger(etudiant khalil,etudiant ait){
    etudiant *pt;
    pt = &khalil ;
    char* n ;
    int p ;
    n = ait.nom ;
    p = ait.cne ;
    ait.cne = pt->cne ;
    ait.nom = pt->nom ;
    khalil.cne = p;
    khalil.nom = n;
}
int main(){
    etudiant khalil ;
    etudiant ait ;
    khalil.cne = 123 ; khalil.nom = "khalil" ;
    ait.cne = 789 ; ait.nom = "ait" ;
    cout << "khalil : nom =>  " << khalil.nom << " ; cne => " << khalil.cne << endl;
    cout << "ait    : nom =>  " << ait.nom << " ; cne => " << ait.cne << endl;
    echanger(khalil,ait);
    cout << "khalil => nom : " << khalil.nom <<" ,cne : " << khalil.cne << endl;
    cout << "ait =>  nom : " << ait.nom <<" ,cne : " << ait.cne << endl;
    return 0;
}

当您使用

void echanger(etudiant khalil,etudiant ait){

您正在将对象的副本传递给 echanger 。对函数中的khalilait所做的任何更改对调用函数不可见。它们是对本地副本的更改。若要使更改在调用函数中可见,函数需要在参数中使用引用类型。

void echanger(etudiant& khalil, etudiant& ait){
//                    ^                 ^

您的参数是按值传递的,因此您只在 main 中更改原始副本。

将函数更改为将参数作为引用(或指针(。

还可以考虑使用 std::swap 而不是实现自己的。