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

swap two structures in c++ using a user function

我有以下代码,对我来说看起来不错 我的目的是交换名称和 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 而不是实现您自己的。