Tutorial Study Image

C++ 中对象传递与返回


2023年5月26日, Learn eTutorial
889

在本教程中,您将通过非常简单的示例,掌握在 C++ 语言中如何将对象传递和返回给函数。我们将通过一些示例学习如何将对象作为参数提供给函数,以及如何从函数返回对象。

C++ 中如何传递和返回对象?

在 C++ 中,类对象的传递和返回方式与普通变量类似。不需要特殊的关键字或头文件。

对象可以像 C++ 中的普通参数一样传递给函数。

将对象作为参数传递给 C++ 函数

为了将对象作为参数传递,在调用函数时,只需像使用其他变量一样使用对象名作为参数。

语法


function_name(object_name);
 

将对象传递给函数。

与将结构体传递给函数类似,我们也可以将对象传递给函数。类 A 中有一个名为 disp() 的函数,它接受类 A 对象作为参数。可以以类似的方式将一个类的对象传递给另一个类的函数。

让我们编写一个 C++ 程序来理解如何将对象传递给函数。


#include <iostream>
using namespace std;
class A {
   public:
    int age = 10;
    char ch = 'A';

    // function  has objects asthe parameters
    void display(A &a) {

       cout << "Age = " << a.age << endl;
       cout << "Character = " << a.ch << endl;

    }
};
int main() {
    A obj;
    obj.display(obj);
    return 0;
}

 

输出


Age = 10
Character = A

示例 2

用于确定两个学生平均年龄的 C++ 程序。


#include <iostream>
using namespace std;
class Student {
   public:
    int age;

    // constructor in order to initialize age
    Student(int a) {
        age = a;
    }
};
// function which has the objects as the parameters
void calculateAverage(Student s1, Student s2) {
    // calculate  average age of s1 and s2 
    int average = (s1.age + s2.age) / 2;

   cout << "Average Age = " << average << endl;

}
int main() {
    Student student1(20), student2(30);
    // pass the objects as arguments
        calculateAverage(student1, student2);

    return 0;
}

 

输出


Average Age = 25

calculateAverage() 函数已将两个 Student 对象 student1 和 student2 作为参数传入。

如何在 C++ 中从函数返回对象?

函数可以按引用或按值返回对象。当函数按值返回对象时,会在函数内部生成一个包含返回值的临时对象。然后,调用函数将此值赋给另一个对象。

定义一个按值返回对象的函数需要以下语法。


class_name function_name (parameter_list) {
 // body of the function
}
 

示例

请看这个示例,以便更好地理解函数返回对象按值传递的概念。

一个说明函数返回对象概念的程序。


#include<iostream.h>
class weight {
  int kilogram;
  int gram;
  public:
    void getdata ();
    void putdata ();
    void sum_weight (weight,weight) ;
    weight sum_weight (weight) ;
} ;
void weight :: getdata() {
  cout<<"/nKilograms:";
  cin>>kilogram;
  cout<<"Grams:";
  cin>>gram;
}
 void weight :: putdata () {
   cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
 }
 weight weight :: sum_weight(weight w2) {
  weight temp;
  temp.gram = gram + w2.gram;
  temp.kilogram=temp.gram/1000;
  temp.gram=temp.gram00;
  temp.kilogram+=kilogram+w2.kilogram;
  return(temp);
}
int main () {
  weight w1,w2 ,w3;
  cout<<"Please enter the weight in kilograms and grams\n";
  cout<<"\n Enter weight #1" ;
  w3 = w1.sum_weight (w2);
  w1.getdata();
  cout<<" \n Enter weight #2" ;
  w2.getdata();
  w3.sum_weight(wl,w2);
  cout<<"/n Weight #1 = ";
  w1.putdata();
  cout<<"Weight #2 = ";
  w2.putdata();
  cout<<"Total Weight Will Be = ";
  w3.putdata();
  return 0;
}

 

由于该方法的返回类型是 weight(weight 类的对象),因此在函数中创建了一个临时对象 temp 来保存返回值。函数以 temp kilogram 和 temp gram 的方式访问这些值。当控制返回到 main() 时,对象 temp 被赋给 main() 中的对象 w3。

该图说明了在函数内访问成员变量以及从临时对象返回结果。

Passing and Returning Objects in C++

当按引用返回对象时,不会构造新对象;相反,调用函数会接收到被调用函数中原始对象的引用。

定义一个按引用返回对象的函数有以下语法


class_name& function_name (parameter_list) {
  //body of the function
}
 

但是,由于对局部数据的引用是指向函数内部的数据,因此函数不能通过引用返回局部对象(在方法内部声明的对象)。因此,当函数结束并且局部数据被删除时,此引用将指向空。


weight& weight::sum_weight(weight& w2) {
  weight temp; //object local to function
  temp.gram=gram+w2.gram;
  temp.kilogram=temp.gram/1000;
  temp.gram=temp.gram00;
  temp.kilogram+=kilogram+w2.kilogram;
  return temp; //invalid
}
 

考虑 sum weight() 函数,已按照此代码部分的说明进行了更新,以理解此概念。

在此代码部分中,已尝试返回 weight 类型对象(即 temp)的引用。但是,这是不可能的,因为对 temp 对象的引用仅在 sum weight() 函数使用它时才有效。因此,将临时对象引用返回到函数外部会导致编译错误。

示例

在此示例中,有两个函数:display() 接受 Student 对象作为参数,input() 将返回 Student 对象。使用 static_cast 运算符来打印 void 指针的内容。它将指针的数据类型从其原始的 void* 类型更改为指针正在存储的地址的相应数据类型。

C++ 编程演示如何将对象返回给函数


#include <iostream>
using namespace std;
class Student {
   public:
    int stId;
    int stAge;
    string stName;

    // In this function we returning the student object
    Student input(int n, int a, string s) {
        Student obj:
        obj.stId = n;
        obj.stAge = a;
        obj.stName = s;
        return obj;
    }
    // In this function we pass object as an argument
    void display(Student obj) {

       cout << "Name = " << onj.stName << endl;
       cout << "Id = " << onj.stId << endl;
       cout << "Age = " << onj.stAge << endl;
    }
};
int main() {
    Student s;
    s = s.input (2005, 50, Alice)
    s.display(s);
    return 0;
}

 

输出


Name = Alice
Id = 2005
Age = 50