C + + Object-oriented (i)-Class (Classes)

Source: Internet
Author: User
Tags class definition

Class is a logical way to organize data and functions in the same structure. The definition class is class, and its functionality is similar to a struct in C, except that class can contain functions, unlike structs that can only contain data elements.

The class definition is in the form of:

    Class Class_name {        permission_label_1:            member1;        Permission_label_2:            member2;        ...    } object_name;  

Where Class_name is the name of the class (the user-defined type), and the optional object_name is one or more objects (object) identifiers. The declaration body of class contains member members, which can be data or function definitions, and can include the Allow range flag permission labels, which can be any of the following three keywords: private:, Public: OR Protected:. They represent the following meanings, respectively:

    • Private members of Private:class, only the other members of the same class or the class's "Friend" class can access these members.
    • Protected:class's protected member, only the other members of the same class, or the class's "Friend" class, or the class's subclass (derived classes) can access these members.
    • The public members of Public:class can access these members anywhere they can see the class.

If we do not declare a class member's allowable scope when we define it, these members will be defaulted to the private scope.

For example:

Class Crectangle {            int x, y;        Public:            void Set_values (int,int);            int area (void);    } Rect    

The above example defines a class Crectangle and an object variable rect of that class type. This class has 4 members: two integer variables (x and Y), in the private section (because private is the default allowable range), and two functions in the public section: Set_values () and area (), which contains only the prototype of the function (proto Type).

note The class name differs from the object name: In the example above, Crectangle is the class name (that is, the user-defined type name), and Rect is the object name of the Crectangle type. The difference is the same as the difference between the type name int and the variable name A in the following example:

int a;

int is the class name (the type name), and a is the object name (variable).

In the program, we can refer to any public member of the object rect, as if they were just general functions or variables, by adding a little bit after the object name and then using the member name (as with C structs). For example:

Rect.set_value (3,4);
Myarea = Rect.area ();

However, we cannot refer to X or y because they are private members of the class and they can only be referenced in other members of the class. Are you dizzy? Here is a complex example of class Crectangle:

 //classes example  #include <iostream.h> cla        SS Crectangle {int x, y;            Public:void set_values (Int,int);    int area (void) {return (x*y);}        };        void Crectangle::set_values (int a, int b) {x = A;    y = b;        } int main () {Crectangle rect;        Rect.set_values (3,4);    cout << "area:" << rect.area (); } 
area:12

The new thing in the code above is the definition function set_values (). The range operator used (double colon::). It is used to define a member of the class outside of a class. Note that we have defined the function area () within the Crectangle class, because this function is very simple. For the function set_values (), only the prototype prototype is defined within class, and its implementation is defined outside the class. This condition that defines its members outside of class must use the scope operator::.

Range operator (::) Declares the class name to which the defined member belongs, and gives the defined member the appropriate range attributes, which are the same as the properties of the member defined within the class. For example, in the above example, we reference the private variable x and y in the function set_values (), which are visible only within class and within its members.

The only difference between defining a complete function directly within class and simply defining the function's prototype and placing the implementation outside the class is that in the first case the compiler (compiler) automatically takes the function as inline, and in the second case, Functions are just general class member functions.

We define X and Y as private members (remember, if there is no special declaration, all class members default to private) because we have defined a function (Set_values ()) that sets these variable values, There is no way to access them directly anywhere else in the program. Perhaps in such a simple example, you can't see the meaning of protecting two variables in this way, but in a more complex program, this is very important, because it makes the variables not accidentally modified (this is accidentally referred to as an object from the point of view of the accident).

One of the bigger benefits of using class is that we can use it to define multiple different objects (object). For example, following the example of class Crectangle above, we can define object RECTB in addition to the object rect:

 //class example  #include <iostream.h>        Class Crectangle {int x, y;            Public:void set_values (Int,int);    int area (void) {return (x*y);}        };        void Crectangle::set_values (int a, int b) {x = A;    y = b;        } int main () {Crectangle rect, RECTB;        Rect.set_values (3,4);        Rectb.set_values (5,6);        cout << "rect area:" << rect.area () << Endl;    cout << "RECTB area:" << rectb.area () << Endl; } 
rect area:12
RECTB area:30

Note : The call to function Rect.area () is not the same as the result of calling Rectb.area (). This is because each class Crectangle object has its own variable x and Y, as well as its own function set_value () and area ().

This is based on the concept of object-and object-oriented programming (Object-oriented programming). In this concept, data and functions are attributes of objects (properties), rather than objects (object) as previously thought in structured programming (structured programming) as function arguments. In this section and later in the subsections, we will discuss the benefits of object-oriented programming.

In this specific example, we discuss the class (type of object) that is Crectangle, with two instances (instance), or object: Rect and RECTB, each with its own member variable and member function.


Constructors and destructors (constructors and destructors)

Objects (object) often need to initialize variables or allocate dynamic memory during the build process, so that we can operate, or prevent unexpected results from being returned during execution. For example, in the previous example, what would happen if we called the function area () before calling the function Set_values ()? May be an indeterminate value because member X and Y have not yet been assigned to any value.

To prevent this from happening, a class can contain a special function: constructor constructor, which can be defined by declaring a function with the same name as class. This constructor is automatically called when and only if you want to generate a new instance of Class (instance), that is, when you declare a new object, or allocate memory to an object of that class. Below, we will implement the Crectangle that contains a constructor:

 //class example  #include <iostream.h>      Class Crectangle {int width, height;        Public:crectangle (Int,int);    int area (void) {return (width*height);}        };        Crectangle::crectangle (int A, int b) {width = A;    height = b;        } int main () {Crectangle rect (3,4);        Crectangle RECTB (5,6);        cout << "rect area:" << rect.area () << Endl;    cout << "RECTB area:" << rectb.area () << Endl; } 
rect area:12
RECTB area:30

As you can see, the output of this example is no different from the previous one. In this case, we just replaced the function set_values with the class's constructor constructor. Notice how the arguments are passed to the constructor when the class instance (instance) is generated:

CRectangle rect (3,4);
CRectangle rectb (5,6);

At the same time you can see that both the prototype and the implementation of the constructor have no return values (return value) and no void type declarations. The constructor must write this way. A constructor never returns a value, nor does it declare void, as we saw in the previous example.

The destructor destructor complete the opposite function. It is automatically called when the objects is freed from memory. The release may be due to the end of its existence (for example, if object is defined as a local (locally) object variable within a function, and the function ends), or because it is a dynamically allocated object and is freed by the use of the operator delete.

The destructor must have the same name as class, plus the tilde (~) prefix and must have no return value.

Destructors are especially useful when an object is dynamically divided into memory space, and when the object is destroyed, we want to release the space it occupies. For example:

 //example on constructors and destructors  #include <iostrea      M.h> class Crectangle {int *width, *height;        Public:crectangle (Int,int);        ~crectangle ();    int area (void) {return (*width * *height);}        };        Crectangle::crectangle (int A, int b) {width = new int;        height = new int;        *width = A;    *height = b;        } crectangle::~crectangle () {delete width;    Delete height;        } int main () {Crectangle rect (3,4), RECTB (5,6);        cout << "rect area:" << rect.area () << Endl;        cout << "RECTB area:" << rectb.area () << Endl;    return 0; }
Rect area:12
RECTB area:30
Constructor overloading (overloading constructors)

Like other functions, a constructor can be overloaded multiple times (overload) as a function of the same name, but with different parameter types and numbers. Remember that the compiler invokes the same function (Section 2.3, FUNCTIONS-II) as the parameter type and number required at the time of the call. Here is the constructor that is called when the class object is declared.

In fact, when we define a class without a definite definition of the constructor, the compiler automatically assumes two overloaded constructors (the default constructor, "constructor" and the copy constructor "copy constructor"). For example, for the following class:

   Class Cexample {public     :       int a,b,c;       void multiply (int n, int m) {a=n; b=m; c=a*b;};   };   

Without a constructor defined, the compiler automatically assumes that it has the following constructor member functions:

    • Empty Constructor

      It is a constructor without any parameters and is defined as NOP (no statement). It doesn't do anything.

      CExample::CExample () { };
    • Copy Constructor

      It is a constructor that has only one parameter, which is an object of this class, and the function is to copy the values of all non-static (non-static) member variables of the object being passed in to this object itself.

        Cexample::cexample (const cexample& RV) {       a=rv.a;  B=RV.B;  c=rv.c;   }   

必须注意:这两个默认构造函数(empty construction 和 copy constructor )只有在没有其它构造函数被明确定义的情况下才存在。如果任何其它有任意参数的构造函数被定义了,这两个构造函数就都不存在了。在这种情况下,如果你想要有empty construction 和 copy constructor ,就必需要自己定义它们。

当然,如果你也可以重载class的构造函数,定义有不同的参数或完全没有参数的构造函数,见如下例子:

        //overloading class constructors  #include <iostream.h>      Class crectangle {int width, height;        Public:crectangle ();        Crectangle (Int,int);    int area (void) {return (width*height);}        };        Crectangle::crectangle () {width = 5;    Height = 5;        } crectangle::crectangle (int a, int b) {width = A;    height = b;        } int main () {Crectangle rect (3,4);        Crectangle RECTB;        cout << "rect area:" << rect.area () << Endl;    cout << "RECTB area:" << rectb.area () << Endl; }
Rect area:12
RECTB area:25

在上面的例子中,rectb 被声明的时候没有参数,所以它被使用没有参数的构造函数进行初始化,也就是width 和height 都被赋值为5。

注意在我们声明一个新的object的时候,如果不想传入参数,则不需要写括号():

CRectangle rectb; // right
CRectangle rectb(); // wrong! 

Pointer to class (pointers to classes)

Classes can also have pointers, and to define pointers to classes, we just need to realize that once a class is defined it becomes a valid data type, so only the name of the class can be used as the name of the pointer. For example:

CRectangle * prect;

is a pointer to an object of class Crectangle type.

Just like in the case of a data organization, you need to use the operator---to directly refer to a member in an object that is pointed to by a pointer. Here is an example that shows several possible scenarios:

    //Pointer to classes example    #include <iostream.h> class Crectangle {int width, height;        Public:void set_values (int, int);    int area (void) {return (width * height);}        };        void Crectangle::set_values (int a, int b) {width = A;    height = b;        } int main () {Crectangle A, *b, *c;        Crectangle * d = new crectangle[2];        b= new Crectangle;        C= &a;        (a.set_values);        B->set_values (3,4);        D->set_values (5,6);        D[1].set_values (7,8);        cout << "A area:" << a.area () << Endl;        cout << "*b area:" << b->area () << Endl;        cout << "*c area:" << c->area () << Endl;        cout << "d[0" area: "<< d[0].area () << Endl;        cout << "d[1" area: "<< d[1].area () << Endl;    return 0; }
A area:2
*b Area:12
*c Area:2
D[0] Area:30
D[1] Area:56

Here is how to read some pointers and class operators (*, &,.,->, []) that appear in the previous example:

    • *x read: Pointed by X (pointed by X)
    • &X read: Address of X (Addresses of X)
    • X.Y read as: member Y of Object X (member y of object X)
    • (*x). Y reads: member Y of object pointed by X (member y of the object pointed by X)
    • X->y read: Member Y of object pointed by X (same previous equivalent)
    • X[0] Read: First object pointed by X (the object that is pointed to by X)
    • X[1] Read: Second object pointed by X (second object pointed by X)
    • X[n] read: (n+1) th object pointed by X (the N+1 object pointed by X)

Before you continue reading down, make sure you understand the logical meaning of all these. If you still have questions, read this laughter section again, or refer to the section "3.3, pointers (pointers)" and "3.5, data structures (structures)" At the same time.


Classes defined by the keyword struct and union

Classes can be defined not only by the keyword class, but also by a struct or union.

Because the concepts of classes and data structures are too similar in C + +, the two-keyword struct and class function almost the same (that is, classes defined in C + + can have member functions, not just data members). The only difference between classes defined by class is that the default access rights for all members of classes defined by class are private, and the default access rights for all members of a struct-defined class are public. In addition, two keywords are the same.

The concept of union differs from the class defined by struct and class, because Union can store only one data member at a time. However, classes defined by Union can also have member functions. The class access permissions defined by union are default to public.

C + + Object-oriented (i)-Class (Classes)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.