雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++類基本語法實例分析

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

類是C++程序設(shè)計非常重要的概念,本文即以實例形式說明了類的常見用法。具體如下:

本測試代碼主要包括以下內(nèi)容:

(1)如何使用構(gòu)造函數(shù);
(2)默認(rèn)構(gòu)造函數(shù);
(3)對象間賦值;
(4)const使用語法;
(5)定義類常量: 一種方法是用enum,另一種方法是使用static。

實例代碼如下:

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

上一篇:擴(kuò)展KMP算法(Extend KMP)

欄    目:C語言

下一篇:字符串的模式匹配詳解--BF算法與KMP算法

本文標(biāo)題:C++類基本語法實例分析

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3461.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有