C++

Topic: struct&class

Lecturer: Lemon

物件導向

  • 封裝性

  • 繼承性

  • 多型

物件導向

結構(Struct)

#include <iostream>
using namespace std;
struct People {
	//接下來會在裡面放咚咚
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
}

語法(寫在main外面)

之後跟int一樣,作為宣告的類別

結構(Struct)

封裝:我們可以把值放在結構中

取用時使用.(變數名)

#include <iostream>
using namespace std;
struct People {
	int age, weight, height;
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
	yeedrag.age = 16;
	yeedrag.weight = 8e7;
	yeedrag.height = 7741;
}

結構(Struct)

封裝:我們可以把函式放在結構中

取用時使用.(函式名)

#include <iostream>
using namespace std;
struct People {
	int age, weight, height;
	int BMI() {
		return weight/(height*height);
	}
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
	yeedrag.age = 16;
	yeedrag.weight = 8e7;
	yeedrag.height = 7741;
	cout << yeedrag.BMI();
}

類別(Class)

語法(寫在main外面)

之後跟int一樣,作為宣告的類別

#include <iostream>
using namespace std;
class People {
	//哈哈我用複製的
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
}

類別(Class)

封裝:我們可以把值放在類別中

和struct不一樣的是

我們有public、private、protected

#include <iostream>
using namespace std;
class People {
	private:
		int weight;
	public:
		int age;
	protected:
		int height;
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
	yeedrag.age = 16;
	//yeedrag.weight = 8e7; 不合法
	//yeedrag.height = 7741; 不合法
}

類別(Class)

public:可以直接存取

private:不能直接存取

protected:可以被其繼承者存取(有緣再講)

#include <iostream>
using namespace std;
class People {
	private:
		int weight;
	public:
		int age;
	protected:
		int height;
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
	yeedrag.age = 16;
	//yeedrag.weight = 8e7; 不合法
	//yeedrag.height = 7741; 不合法
}

類別(Class)

雖然private、protected不能直接存取

但可以透過類別內函式取用、修改

#include <iostream>
using namespace std;
class People {
	private:
		int weight;
	public:
		int age;
		int get_weight() {
			return weight;
		}
		void set_weight(int w) {
			weight = w;
		}
}; 
//記得打分號ㄛ

int main() {
	People yeedrag; // yeedrag就是一個People物件
	yeedrag.age = 16;
	yeedrag.set_weight(100000);
	cout << yeedrag.get_weight();
	return 0;
}

建構式

無論class 抑或 struct 都有constructor

作用是把物件初始化

語法如下(用自己的名字當函數):

#include <iostream>
using namespace std;
class Point {
	private:
		int x, y, z;
	public:
		//用自己的名字當函數
		Point(int _x, int _y, int _z): x(_x), y(_y), z(_z) {
			//這裡面也可以放咚咚
		}
}; 
//記得打分號ㄛ

int main() {
	Point A(1, 3, 2); // A是一個Point物件
}

建構式

適當的使用建構式可以使程式更加易讀

但在平常寫Code

或者在打競賽的時候

可能也不一定會用到w

你們就當補充ㄅ

BTW

這些東西顯然一節課講不完

但如果想了解更多

可以查運算子多載、類別繼承

這樣你的code就會很毒瘤

範例

請利用struct或class實作分數的加減法(挑戰題)

ZJ b538

請利用struct或class實作分數比大小

沒有Judge QAQ

講師段考燒雞QAQ

ㄅㄅ

Struct&Class

By lemonilemon

Struct&Class

  • 195