请如何通过引用和值传递结构? [英] How to pass a struct by reference and by value, please?

查看:84
本文介绍了请如何通过引用和值传递结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有这个;

for example I have this one;

struct students {
   string name;
   int ID;
   char Grade;
};

students undergraduates,graduates;



我想将其传递给函数怎么办?谢谢:)



I want to pass it to a function what to do? thanks :)

推荐答案

方法如下:

Here is how:

struct Student { //use singular, not plural
   //...
}

Student first, second; 

void PassByValue(Student who); //prototype
void PassByReference(Student& who); //prototype

PassByValue(first); //you work with a shallow copy of "who, if you changes is, actual object remains the same
PassByReference(second); //no copy (faster), when you modify who you modify actual passed object



调用是相同的,但第二个调用始终需要一个变量.
结构与否-不管怎样,都可以是任何类型.

-SA



Call is identical, but second call always needs a variable.
Structure or not — no matter, can be any type.

—SA


typedef struct _STUDENT
{
   string    name;
   int      ID;
   char      Grade;
} STUDENT;
void fnStruct(STUDENT student)
{
  // you can everything you want
  // the value from caller is not affected
}
void fnStructRef(STUDENT& student)
{
  // you can read or write values
  // the value from the caller can be modified
  // usually a ref cannot be a null pointer
}
void fnStructConstRef(const STUDENT& student)
{
  // you can only read the members
  STUDENT*  writable = (STUDENT*)&student;
  // this construct makes it possible to full access
  // the value from the caller will be modified
}
void fnStructPtr(STUDENT* student)
{
  // you can read or write values
  // the value from the caller can be modified
  // the pointer can be a null pointer
  if(student)
  {
    // the param is not null
  }
}
void fnStructConstPtr(const STUDENT* student)
{
  // you can only read the members
  // the pointer can be a null pointer
  if(student)
  {
    // the param is not null
    STUDENT*  writable = (STUDENT*)student;
    // this construct makes it possible to full access
    // the value from the caller will be modified
  }
}
void main()
{
  STUDENT   undergraduates,
            graduates;
  // parameter cannot be changed in any circumstances
  fnStruct(undergraduates);
  // parameter can be changed
  fnStructRef(undergraduates);
  // parameter should not be changed, but it can
  fnStructConstRef(undergraduates);
  // parameter can be changed
  fnStructPtr(&undergraduates);
  // parameter should not be changed, but it can
  fnStructConstPtr(&undergraduates);
}


问候.


这篇关于请如何通过引用和值传递结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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