类的声明,定义及使用

类(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;
}

运行结果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,头文件用于声明定义声明的目的是为了在其他文件中使用,而不需要暴露的具体实现细节。头文件通常包含的成员函数和成员变量的声明。 头文件中声明时,一般包括的关键字(class)和名。例如,声明一个名为Person的可以写成以下形式: ```cpp class Person { // 的成员变量和成员函数的声明 }; ``` 在头文件中,我们可以声明的成员变量和成员函数。例如,下面的例子声明了一个Person,其中包含了两个私有成员变量(name和age),以及两个公有成员函数(setName和setAge): ```cpp class Person { private: string name; // 姓名 int age; // 年龄 public: void setName(string name); // 设置姓名 void setAge(int age); // 设置年龄 }; ``` 在头文件中,我们还可以定义的成员函数。定义成员函数是为了给函数提供具体的实现。例如,我们可以在头文件中定义上述Person的成员函数: ```cpp class Person { private: string name; // 姓名 int age; // 年龄 public: void setName(string name) { this->name = name; } void setAge(int age) { this->age = age; } }; ``` 头文件中的声明可以在多个源文件中使用,只需要包含该头文件即可。例如,在其他源文件中使用Person时,只需要包含头文件即可: ```cpp #include "person.h" int main() { Person p; p.setName("Tom"); p.setAge(20); return 0; } ``` 总而言之,头文件主要用于声明定义,以便在其他文件中使用。通过头文件,我们可以在不暴露的具体实现细节的情况下使用的成员变量和成员函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值