C++對象和類

由於C++是一種面向對象的語言,程式可使用C++中的對象和類來設計。

C++對象

在C++中,對象是一個真實世界的實體,例如:椅子,汽車,筆,手機,筆記本電腦等。換句話說,對象是一個具有狀態和行為的實體。 這裏,狀態意味著數據,而行為意味著功能。
對象是一個運行時實體,它在運行時創建。

對象是類的一個實例。 類的所有成員都可以通過對象訪問。下麵來看看一個使用s1作為引用變數創建Student類對象的示例。

Student s1;  //creating an object of Student

在此示例中,Student是類型,s1是引用Student類的實例的引用變數。

C++類

在C++中,對象是一組相似的類。 它是一個範本,用於從中創建對象。 它可以有字段,方法,構造函數等。

下麵來看看一個只有三個字段的C++類的例子。

class Student
 {
     public:
         int id;  //field or data member
         float salary; //field or data member
         String name;//field or data member
 }

C++對象和類示例

下麵來看看一個有兩個字段的類的例子:idname。 它創建類的實例,初始化對象並列印對象值。

#include <iostream>
using namespace std;
class Student {
   public:
      int id;//data member (also instance variable)
      string name;//data member(also instance variable)
};
int main() {
    Student s1; //creating an object of Student
    s1.id = 201;
    s1.name = "Xiaoniu Su";
    cout<<s1.id<<endl;
    cout<<s1.name<<endl;
    return 0;
}

執行上面代碼,得到如下結果 -

201
Xiaoniu Su

C++類示例:通過方法初始化和顯示數據

下麵來看看看另一個C++類的例子,我們通過方法初始化並顯示對象。

#include <iostream>
using namespace std;
class Student {
   public:
       int id;//data member (also instance variable)
       string name;//data member(also instance variable)
       void insert(int i, string n)
        {
            id = i;
            name = n;
        }
       void display()
        {
            cout<<id<<"  "<<name<<endl;
        }
};
int main(void) {
    Student s1; //creating an object of Student
    Student s2; //creating an object of Student
    s1.insert(201, "Wei");
    s2.insert(202, "Hema");
    s1.display();
    s2.display();
    return 0;
}

執行上面代碼,得到如下結果 -

201  Wei
202  Hema

C++類示例:存儲和顯示員工資訊

下麵來看看看另一個C++類的例子,使用方法存儲和顯示員工的資訊。

#include <iostream>
using namespace std;
class Employee {
   public:
       int id;//data member (also instance variable)
       string name;//data member(also instance variable)
       float salary;
       void insert(int i, string n, float s)
        {
            id = i;
            name = n;
            salary = s;
        }
       void display()
        {
            cout<<id<<"  "<<name<<"  "<<salary<<endl;
        }
};
int main(void) {
    Employee e1; //creating an object of Employee
    Employee e2; //creating an object of Employee
    e1.insert(201, "Wei",990000);
    e2.insert(202, "Hema", 29000);
    e1.display();
    e2.display();
    return 0;
}

執行上面代碼,得到以下結果 -

201  Wei  990000
202  Hema  29000

上一篇: C++面向對象概念 下一篇: C++ this指針