一個Class中的element可以分為public和private:
- public:當外部欲操控某個class instance(被定義為某一class的物件),只能讀取其中為private的變數(在此我們叫他屬性,attribute)或函式
- private:指有class內部的statement可以使用的變數或是函式
被定義為某一class的物件,我們稱作instance,每一個物件都有可能有他的屬性、函式可以讀取、呼叫。例如一個被定義為學生的物件,他就可能有他的名字、成績、年級等為他的屬性,而修改他的成績、印出他的成績、更改他的名字則是他有可能的函式。
程式設計過程中我們盡可能把一個class物件包裝的好好的,不需要也不該讓使用該物件的人看到的東西就隱藏起來(設成private),而要更改的話就呼叫set程式,如a.setName("Heron"),讀取private變數的話,a.getName()。
最後,每一個class都會有一個constructor(如果自己沒有定義,則系統會使用預設的,即沒有做什麼事),constructor的功能為初始化class裡面的變數,當有任何一個instance被定義為該class的時候constructor就會被執行,注意以下兩點:
- constructor是class裡面的一個function,但是他不會回傳值,所以沒有資料型態
- constructor的function name要跟class名稱一樣,compiler才知道這個是constructor
- 當有任何一個instance被定義為該class的時候constructor就會被執行
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
// constructor
Student(string name){
studentName = name;
}
// set funtion
void setName(string name){
studentName = name;
}
// get funtion
string getName(){
return studentName;
}
private:
string studentName;
};
int main(){
Student a("Heron Yang");
cout << "Student a's name is " << a.getName() << "." << endl ;
a.setName("A Smart Guy");
cout << "Student a's name is " << a.getName() << "." << endl ;
// we can not access the private attribute of the class, like:
// cout << a.studentName;
return 0;
}
http://www.ziyou.math.ncu.edu.tw/~ziyou/c++/
ReplyDelete我覺得這網站資料還不錯
另外
不考慮用WORDPRESS嗎XDD?
我用Blog Spot一陣子了,感覺都還不錯呀 :)
ReplyDelete