1. 程式人生 > >類的宣告,定義及使用

類的宣告,定義及使用

類(Class)是一種資料型別,即符合該型別的資料都可以歸到你定義的類中。所以要定義一個類,就必須弄清楚其特點及其作用。計算機軟體各種功能不再是簡單的四則運算能實現的了,因此,需要建立區別與int、char、bool等資料型別的新資料型別——類,來實現更復雜的運算。

當然,不使用類也能完成複雜的運算,面向物件的概念出現之前就是靠工程師們強大的邏輯思維來實現的。但是當面向物件的程式設計思想出現後,類出現後,核心的技術人員將各個相同屬性的資料封裝成類,形成一個個物件,令上層的開發人員能直接通過對各物件進行排程來開發軟體。

這就好比積體電路,大量閘電路整合(封裝)為加法器,觸發器等邏輯電路。而各種邏輯電路又整合(封裝)為放大器,比較器等單元電路。而大量單元電路整合(封裝)為CPU,RAM,ROM。上層的設計師不瞭解內部構造,也不能修改封裝好的物件,但不影響其使用。反而加快了開發效率。這就是面向物件的程式設計思想,這就是類的作用。

本次實驗使用Visual Studio 2012,建立一個貨幣類,並且使用它。
例子來源:《資料結構、演算法與應用 C++語言描述》機械工業出版社

建立專案及相應的標頭檔案,源程式檔案

TheClass.h

/****************************************************************
*Name:         TheClass.h
*Content:      The definition of currency and illegalParameterValue
*Instructions: Used to define some classes
*Version:      V1.0
*Author:       Caddress
*Data:         20160226
***************************************************************/
#pragma once #include<stdio.h> #include<iostream> #include<string> using namespace std; //Define an enumerated type enum signType{plus, minus}; /********************************************************** *Class: currency *Members: amount *Instructions: Class about currency *Data Version Author Content *---------------------------------------------------------- *20160226 V1.0 Caddress Declaration ***********************************************************/
class currency { public: //The constructor definition currency(signType theSign = plus, unsigned long theDollars = 0, unsigned int theCent = 0); //The destructor ~currency() {} //Two member function for assignment void setValue(signType, unsigned long, unsigned int); void setValue(double); //Get the currency symbol signType getSign() const {if (amount < 0) return minus; else return plus;} //Get the dollar value unsigned long getDollars() const {if (amount < 0) return (-amount)/100; else return amount / 100;} //Get the cent value unsigned int getCents() const {if (amount < 0) return -amount - getDollars() * 100; else return amount - getDollars() * 100;} //Reloading the "+" operator currency operator+(const currency&) const; //Reloading the "+=" operator currency operator+=(const currency& x) {amount += x.amount; return *this;} //For the output in the specified format void output(ostream&) const; private: long amount; }; /********************************************************** *Class: illegalParameterValue *Members: message *Instructions: Class about Anomaly detection *Data Version Author Content *---------------------------------------------------------- *20160226 V1.0 Caddress Declaration ***********************************************************/ class illegalParameterValue { public: illegalParameterValue(): message("Illegal parameter value"){} illegalParameterValue(char* theMessage) {message = theMessage;} void outputMessage() {cout << message << endl;} private: string message; }; //The constructor definition currency::currency(signType theSign, unsigned long theDollars, unsigned int theCents) { setValue( theSign, theDollars, theCents); } //Three parameters initialization void currency::setValue(signType theSign, unsigned long theDollars, unsigned int theCents) { if(theCents > 99) throw illegalParameterValue("Cents should be < 100"); amount = theDollars * 100 + theCents; if(theSign == minus) amount = -amount; } //Single parameter initialization void currency::setValue(double theAmount) { if (theAmount < 0) amount = (long) ((theAmount - 0.001) * 100); else amount = (long) ((theAmount + 0.001) * 100); } //Reloading the "+" operator.The definition. currency currency::operator+(const currency& x) const { currency result; result.amount = amount + x.amount; return result; } //The definition of output function. void currency::output(ostream& out) const { long theAmount = amount; if (theAmount < 0) {out << '-'; theAmount = -theAmount;} long dollars = theAmount / 100; out << '$' << dollars << '.'; int cents = theAmount -dollars * 100; if(cents < 10) out << '0'; out << cents; } //Reloading the "<<" operator.The definition. ostream& operator<<(ostream& out, const currency& x) { x.output(out); return out;}

TheClass.cpp

/********************************************************************
*Name:         TheClass.cpp
*Content:      main function
*Instructions: Testing can be used currency class normally
*Version:      V1.0
*Author:       Caddress
*Data:         20160226
*********************************************************************/
#include "TheClass.h"

/**********************************************************
*Function:     main
*Input:        void
*Output:       string of results
*Return:       0
*Data          Version      Author          Content
*----------------------------------------------------------
*20160226      V1.0         Caddress        create
***********************************************************/
int main()
{
    currency g, h(plus, 3, 50), i, j;


    g.setValue(minus, 2, 25);
    i.setValue(-6.45);


    j = h + g;

    cout << h << " + " << g << " = " << j << endl;


    j = i + g + h;
    cout << i << " + " << g << " + " << h << " =" << j << endl;


    cout << "Increment " << i << " by " << g << " and then add " << h << endl;

    j = (i += g) + h;
    cout << "Result is " << j << endl;
    cout << "Incremented object is " << i << endl;


    cout << "Attempting to initialize with cents = 152" << endl;
    try {i.setValue(plus, 3, 152);}
    catch (illegalParameterValue e)
    {
        cout << "Caught thrown exception" << endl;
        e.outputMessage();
    }
    getchar();
    return 0;
}

執行結果