類是C++程序設(shè)計非常重要的概念,本文即以實(shí)例形式說明了類的常見用法。具體如下:
本測試代碼主要包括以下內(nèi)容:
(1)如何使用構(gòu)造函數(shù);
(2)默認(rèn)構(gòu)造函數(shù);
(3)對象間賦值;
(4)const使用語法;
(5)定義類常量: 一種方法是用enum,另一種方法是使用static。
實(shí)例代碼如下:
#include <iostream>using namespace std;enum sexType{ MAN, WOMAN};class Human{ //the default is private private: string name; sexType sex; int age; //(5) 定義類常量: 一種方法是用enum,另一種方法是使用static enum{LEN=1}; static const int LEN2 = 3; public: //如果類定義中沒有提供任何構(gòu)造函數(shù),則編譯器提供默認(rèn)構(gòu)造函數(shù)。但,如果類中定義了構(gòu)造函數(shù),那么編寫者必須同時提供一個默認(rèn)構(gòu)造函數(shù)。 //有兩種方法提供默認(rèn)構(gòu)造函數(shù): //(1) 定義一個沒有參數(shù)的構(gòu)造函數(shù):Human(); //(2) 為非默認(rèn)構(gòu)造函數(shù)的參數(shù)提供默認(rèn)值: Human(string m_name="no name", int m_age=0, sexType m_sex=MAN); //兩種定義方式只能二選一 Human(); Human(string m_name, int m_age, sexType m_sex); Human(int m_age); ~Human(); //定義在類聲明中的方法為內(nèi)聯(lián)方法。也可以使用inline關(guān)鍵字將函數(shù)定義在類聲明外部。 void show() const //const加在函數(shù)名后面表示該函數(shù)不會修改該類的數(shù)據(jù)成員。 { cout<<"This is "<<name<<", sex: "<<sex<<", "<<age<<" Years old."<<endl; }};Human::Human(){ cout<<"default construct function"<<endl;}Human::Human(string m_name, int m_age, sexType m_sex){ cout<<"construct function: "<<m_name<<endl; name = m_name; age = m_age; sex = m_sex;}Human::Human(int m_age){ age = m_age;}Human::~Human(){ cout<<"destroy function: "<<name<<endl;}int main(){ cout << "This is test code of C++ class: "<< endl; { //(1) use of construct function Human jack = Human("Jack", 30, MAN); //顯示調(diào)用 Human jerry("Jerry", 26, MAN); //隱式調(diào)用 Human *pTom = new Human("Tom", 10, MAN); //New調(diào)用 //當(dāng)構(gòu)造函數(shù)只有一個參數(shù)時,可以直接用賦值語句賦值。只有一個參數(shù)的構(gòu)造函數(shù)將會被自動調(diào)用 Human marry = 11; //賦值調(diào)用 //(2) defaults construct function Human Lucy; //(3) 賦值對象 Human James; James = Human("James", 28, MAN); //創(chuàng)建一個臨時對象James,copy一份兒該對象賦值給James變量。緊接著該臨時對象會被銷毀。 //(4) const const Human Thomas("Thomas", 29, MAN); Thomas.show(); //The show method must define with 'const' } return 0;}程序運(yùn)行結(jié)果為:

新聞熱點(diǎn)
疑難解答