C++类的描述

类的描述分为两个部分,public和private

public可以用来定义函数,对类的对象进行操作,对于用户是可见的,是用户对对象操作的唯一手段。

private部分用于定义函数和数据成员,这些函数和数据成员对于用户是看不见的

借助于public与private部分,可以让用户只看到他们需要看到的部分,把其他信息隐藏起来。尽管C++语法允许在public部分定义数据成员,但在软件工程实践中不鼓励这种做法。

C语言中将基本数据类型划分为signed(有符号)和unsigned(无符号)两大类。

int a; 等价于 signed int a;

enum sign{ plus,minus};
class Currency{
    public:
        //构造函数 
        Currency(sign s=plus,unsigned long d=0,unsigned int c=0 );
        //析构函数
        ~Currency(){}
    private:
        sign sgn;
        unsigned long dollars;
        unsigned int cents; 
}; 
View Code

public 第一个函数与Currency类同名,称为构造函数。指明如何创建一个给定类型的对象,它不可以有返回值。创建对象时,构造函数被自动唤醒。

析构函数:Currency对象超出作用域时自动调用析构函数,用于删除对象,不可能有返回值。

#include<iostream>
//using namespace std;

enum sign{ plus,minus};
class Currency{
    public:
        //构造函数 
        Currency(sign s=plus,unsigned long d=0,unsigned int c=0 );
        //析构函数
        ~Currency(){}
        bool Set(sign s,unsigned long d,unsigned int c);
        Currency Add(const Currency & x) const; //返回的是指 
        Currency& Increment(const Currency& x);//返回的是引用 
        void output() const;
    private:
        sign sgn;
        unsigned long dollars;
        unsigned int cents; 
}; 

Currency::Currency(sign s,unsigned long d,unsigned int c){
    sgn=s;dollars=d,cents=c;
}
bool Currency::Set(sign s,unsigned long d,unsigned int c){
    if(c>99) return false;
    sgn=s;
    dollars=d;
    cents=c;
}
Currency Currency::Add(const Currency& x) const{
long a1,a2,a3;
Currency ans;
return ans;
}
Currency& Currency::Increment(const Currency& x){
    *this=Add(x); //*this就是当前对象 
    return *this;
}

void Currency::output()const {
std::cout<<dollars<<" "<<cents<<" "<<sgn<<" ";
} 
View Code

重载操作符; Currency包含多个与C++标准操作符相类似的成员函数,可以直接利用C++标准操作符操作

友元函数:将private成员的访问权限授予其他类和函数,就需要将其定义为友元。

posted @ 2019-02-05 16:54  Hello_World2020  阅读(803)  评论(0编辑  收藏  举报