使用用户函数在 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
。对函数中的khalil
和ait
所做的任何更改对调用函数不可见。它们是对本地副本的更改。若要使更改在调用函数中可见,函数需要在参数中使用引用类型。
void echanger(etudiant& khalil, etudiant& ait){
// ^ ^
您的参数是按值传递的,因此您只在 main 中更改原始副本。
将函数更改为将参数作为引用(或指针(。
还可以考虑使用 std::swap 而不是实现自己的。
相关文章:
- 结构包含在两个头文件中,这两个文件我都不拥有
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在两个.cpp文件之间定义全局类/结构指针
- 在两个结构之间共享数组
- C++ 如何从函数传递两个结构?
- C++ 如何在包含两个变量的结构中存储与变量不同数量的值?
- 是否可以使一个类成为两个不同层次结构的子类?
- 如何将值添加到嵌套结构中,该结构在C++中有两个指针
- 如何在单个 SET 中比较结构的两个属性?
- 如何认为两个结构相等,而不管它们的第二个属性如何?
- C 类内部结构和两个呼叫同时
- 首选数据结构,如果您有两个键并且无法使用Boost
- 使用用户函数在 C++ 中交换两个结构
- 是否可以分配两个不同类型的结构
- 如何将比较运算符应用于两个匿名结构中的每个变量
- 在两个程序中,传递指向结构的指针的行为不同
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- C 中的内存模型:为什么在同一内存位置分配了结构中的两个整数
- 在CPP中互相访问的两个结构
- 代码解释 C++ [结构 / 两个 diamentinal 数组 / 指针]