c++对象

来源:互联网 发布:武工队后勤部淘宝店铺 编辑:程序博客网 时间:2024/06/05 16:54

C++程序设计(c++对象)

What is an object?

Object is variable in programming languageObjects=Attributes+ServicesObject consists of Data and Operations      1.Date:the properties or status2.Operations:the functions

示例1

创建一个c++类:

class pointer{   public:    pointer();//定义构造方法,方法默认在创建对象时执行    void show();//定义一个公有方法   private://定义私有成员    int a;    int b;    int c;};

创建一个pointer对象

pointer test=new pointer();

面对对象的理念

  • Objects send and receive messages (objects do things!)

    • Messages are–Composed by the sender–Interpreted by the receiver–Implemented by methods• Messages    • May cause receiver to change state    • May return results
  • class-defines>object object-is>class

    • Objects (cat)  • Represent things, events, or concepts  • Respond to messages at run-time• Classes (cat class)  • Define properties of instances  • Act like types in C++

oop Characteristics

    1.Everything is an object.    2.A program is a bunch of objects telling each what to do by sending messages.    3.Each object has its own memory made up ofother objects.    4.Every object has a type.    5.All objects of a particular type can receivethe same messages  

The Hidden Implementation

  • Inner part of an object, data members to present
    its state, and the actions it takes when messages
    is rcvd is hidden
  • Class creators vs. Client programmers


    –Keep client programmers’ hands off portions they should not touch.


    –Allow the class creators to change the internal working
    of the class without worrying about how it will affect the client programmers

示例2

利用面对对象显示初始化时间

#include<iostream>using namespace std;   class Numbershow{   private:    int limit;    int value;   public:    Numbershow(int limit,int value){        this->limit=limit;        this->value=value;    }    int printnum(){        return value;    }};class Clockshow{    private:    Numbershow min;    Numbershow hour;    public:    //在构造函数中采用参数初始化表    Clockshow(int m,int h):min(60,m),hour(12,h){        cout<<"初始化时间"<<hour.printnum()<<":"<<min.printnum()<<endl;    }};int main(){    Clockshow clock(8,9);    return 0;}

结果

初始化时间9:8
0 0
原创粉丝点击