工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> C言語

C++関数からオブジェクトを渡したり返す方法は?

C++ 関数からオブジェクトを渡したり返したりする方法

このチュートリアルでは、C++ プログラミングでオブジェクトを関数に渡し、関数からオブジェクトを返す方法を学びます。

C++ プログラミングでは、通常の引数を渡すのと同様の方法でオブジェクトを関数に渡すことができます。

例 1:C++ でオブジェクトを関数に渡す

// C++ program to calculate the average marks of two students

#include <iostream>
using namespace std;

class Student {

   public:
    double marks;

    // constructor to initialize marks
    Student(double m) {
        marks = m;
    }
};

// function that has objects as parameters
void calculateAverage(Student s1, Student s2) {

    // calculate the average of marks of s1 and s2 
    double average = (s1.marks + s2.marks) / 2;

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

}

int main() {
    Student student1(88.0), student2(56.0);

  // pass the objects as arguments
   calculateAverage(student1, student2);

    return 0;
}

出力

Average Marks = 72

ここでは、2 つの Student を渡しています。 オブジェクト student1学生2 calculateAverage() への引数として 関数。

<図>

例 2:関数からの C++ 戻りオブジェクト

#include <iostream>
using namespace std;

class Student {
   public:
    double marks1, marks2;
};

// function that returns object of Student
Student createStudent() {
    Student student;

    // Initialize member variables of Student
    student.marks1 = 96.5;
    student.marks2 = 75.0;

    // print member variables of Student
    cout << "Marks 1 = " << student.marks1 << endl;
    cout << "Marks 2 = " << student.marks2 << endl;

    return student;
}

int main() {
    Student student1;

    // Call function
    student1 = createStudent();

    return 0;
}

出力

Marks1 = 96.5
Marks2 = 75
<図>

このプログラムでは、関数 createStudent() を作成しました。 Student のオブジェクトを返す クラス。

createStudent() を呼び出しました main() から メソッド。

// Call function
student1 = createStudent();

ここでは、createStudent() によって返されたオブジェクトを格納しています。 student1 のメソッド .


C言語

  1. 3Dプリントの3つの段階とその仕組み
  2. C# クラスとオブジェクト
  3. C++ クラスとオブジェクト
  4. C++ メモリ管理:新規および削除
  5. C++ の公開、保護、非公開の継承
  6. C++ フレンド関数とフレンド クラス
  7. C パスのアドレスとポインター
  8. C++ 関数とプログラム例
  9. サイバー犯罪、自然災害などからサプライチェーンを保護する方法
  10. C++ 日付と時刻
  11. C++ オーバーロード (演算子と関数)