iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
自我挑戰組

C++入門即放棄系列 第 19

[DAY19]不一樣的傳遞!

  • 分享至 

  • xImage
  •  

物件陣列(Array of Objects)

📌 之前我們學過「陣列」可以放一堆數字,現在,我們也可以用「陣列」放一堆物件

一間班級有很多學生,每個學生都是一個物件,用陣列就能一次管理

#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    void setData(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name;
	        cout << ", 年齡: " << age << endl;
	    }
};
int main() 
{
    Student students[2]; 
    students[0].setData("小A", 12);
    students[1].setData("小B", 13);
    for (int i = 0; i < 2; i++) 
    {
        students[i].display();
    }
    return 0;
}

物件傳遞(Passing Objects)

📌 函式的參數不只能傳整數、字串,也可以傳物件

傳值(by value)

複製一份物件給函式

#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    Student(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name << ", 年齡: " << age << endl;
	    }
};
void show(Student s) 
{
    s.display();
}
int main() 
{
    Student s1("小A", 12);
    show(s1);  
    return 0;
}

傳址/傳參考(by reference)

把原本的物件交給函式操作

#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    Student(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void display() 
	    {
	        cout << "姓名: " << name; 
	        cout << ", 年齡: " << age << endl;
	    }
	    void growUp() 
	    {
	        age++;
	    }
};
void birthday(Student &s) 
{
    s.growUp();
}
void show(Student s) 
{
    s.display();
}
int main() 
{
    Student s1("小A", 12);
    birthday(s1); 
    show(s1);
    return 0;
}

結論

物件陣列讓我們能同時管理多個物件

就像一個班級管理許多學生

而物件傳遞則讓我們可以把物件交給函式處理

在傳遞時,要注意是傳值還是傳參考

這會決定物件是否真的被修改

傳值像是交出一份影印本,改了也不會影響原本的物件

傳參考則像是直接拿到正本,改了就會影響原始物件


上一篇
[DAY18]沒有錯!就是你!
下一篇
[DAY20]函式的組裝與拆解!
系列文
C++入門即放棄21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言