国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++類基本語法實(shí)例分析

2020-01-26 15:23:24
字體:
供稿:網(wǎng)友

類是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é)果為:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 兴安县| 满城县| 黔东| 新化县| 安康市| 务川| 九龙坡区| 漳平市| 碌曲县| 漳平市| 嵩明县| 运城市| 武平县| 内乡县| 临澧县| 邻水| 万山特区| 石楼县| 容城县| 德昌县| 荆门市| 无棣县| 郓城县| 商南县| 绥阳县| 万载县| 静海县| 瓮安县| 平潭县| 凭祥市| 开鲁县| 遂昌县| 石棉县| 奇台县| 哈尔滨市| 上林县| 克拉玛依市| 凤阳县| 尉犁县| 永寿县| 灌阳县|