An in-depth analysis of classes and objects "finishing"

Source: Internet
Author: User
Tags class definition least privilege
relationships between classes and objects

The relationship between a class and an object is like a design diagram and a house relationship--Class 10 constructs the object's "design" of the class. Just as a design can make a lot of houses, but it is impossible to live in the design, we can't use the class directly, but we can instantiate (create) Many objects by a class. Object

Looking at the real world, you can see objects everywhere--people, animals, cars and so on. These objects all have something in common:
1. They all have attributes: size, shape, color, etc.
2. They all have behavior: such as the ball rolling, bouncing, people walking, sleeping, car acceleration, turning, etc.

In C + +, an object is instantiated by a class, so you can assume that the object contains data and functions, although this is not actually the case:
If you perform a sizeof operation on the class name of a class or an object of that class, the result will only contain the size of the data member of the class. class

In object-oriented languages such as C + +, programming focuses on classes , which focus on creating your own user-defined types

These user-defined types are called classes

A class contains: data member: For example, a bank account class may contain account and balance member functions: This is also referred to as a method in other object-oriented languages, such as a bank account class that may include deposits, withdrawals, Query and so on member function definition class

Class gradebook{public
    :
        void DisplayMessage () {
            cout << ' Welcome to the Grade book! ' << endl;< c11/>}
    Private:
        string coursename;
Start the definition of a class with the keyword class by convention, the name of a user-defined class begins at the end of the class definition with a semicolon (;) Defining a function within another function is the invocation of a function within a syntax error class using ".", such as Gradebook GB; Gb.displaymessage (); Public and Private

The member access specifier (public,private, etc.) must be preceded by a colon (:) Public

Public indicates that the function or data is "public use", that is, it can be invoked by other functions in the program or by member functions of other classes (used) private

Variables or functions declared after the member access descriptor is private can only be accessed by the member function of the class that declares them, and cannot be accessed by functions outside the class or by member functions of other classes
-recognition of graphs using expressions such as mygradebook.coursename to access data member Coursename will result in compilation errors
-Functions and classes that are friends of a class that can access private members of the class
- Get functions and set functions to access and manipulate data members is a good way to become a custom object initialization--constructors

To initialize a data member while we create an object, you can use the constructor

In fact, even if we do not explicitly define a constructor, the compiler implicitly creates a default constructor that does not initialize the data members of the class, so these member variables usually contain a "garbage" value, such as-237538
So we'd better customize a constructor that has arguments

Note the following: the constructor and its similar name constructors specify in its parameter list that the data constructors it needs to run can have default arguments, such as Class time1{Time1 (int = 0, int = 0, int = 0)}; Constructors cannot return any value (even void) Normally, the constructor is declared as a complement to the public constructor--destructors

When an object is revoked, the destructor of the class is called implicitly, such as when the object's scope is left
In fact, the destructor itself does not release the memory space occupied by the object, and its knowledge performs a dirty work before the system reclaims the object's memory space, so that the memory can be used again to save the new object. Destructors do not receive any parameters and do not return any value destructors you cannot specify a return type, including void a class can have only one destructor, and the destructor does not allow the overload function to terminate abnormally, without invoking the destructor

Class a{public
    :
        A (int, string);   Constructor
        ~a ();               destructor
    private:
        int id;
        string name;
};
separation of the definition of a class
/* Class Interface
   GradeBook.h *
/#include <string>
using namespace std;

Class gradebook{public
    :
        gradebook (string);
        void Setcoursename (string);
        String Getcoursename ();
    Private:
        string coursename;
};

/* Class definition
   gradebook.cpp*/
#include <iostream>   
using namespace std;

#include "GradeBook.h"

//constructor
Gradebook::gradebook (string name) {
    setcoursename (name);
}
void Gradebook::sercoursename (string name) {
    coursename = name;
}
String Gradebook::getcoursename () {return
    coursename;
}
Compiling and connecting

Don't elaborate.
in-depth analysis of the class Const objects and const member functions

The programmer can use the keyword const to specify that the object is not modifiable , so that any mapping modification of the object will result in a compilation error, such as const time Noon (12,0,0);
Declaring an object as a const helps implement the principle of least privilege and can even improve performance

The method of using const is:
//const object
const int hour;
const function
int getTime () const{return
    hour;
}

When we use const to define an object or member function, we should pay attention to the following points:
1. The compiler does not allow a member function declared as const to modify the object, so defining the member function of the data member of the modified object as const will result in a compilation error
2. A const member function must not call a non-const member function of the same instance of the same class
3. A const object must not invoke a non-const member function
4. Constructors and destructors modify objects, so const declares const data members to constructors and destructors is not allowed

All data members can be initialized with the member initializer, and the const object cannot be initialized by assignment, so the const data member and the referenced data member must be initialized with the member initializer

The position of the member initializer is similar to the const in the constructor's argument list and the left curly brace, and is initialized with a colon (:) separated from the argument list: the name of the data member and the initialization value contained in the parentheses, as follows:
class add{public
:
    Add (int c=0,int i=0)
        : Count (c),
         increment (i)
    {
        //empty
    }
private:
    int Count;
    const int increment;
};
It is a good programming practice to declare all the member functions of the runtime without modifying the object as const composition (composition)

Composition is a class that takes objects of other classes as members
A data member of a class type initializes the object of the class with the method of the member initializer, which is created from the inside out. The first is to create the class object within the class, and then the Undo (destructor) of the object that created the class class is in the exact opposite order, that is, from the outside, the destructor friend function and the friend class

The friend function is defined outside the scope of the class, but it has permission to access all members of the class, but it is not a member function

The definition of the friend function
class count{
    friend void SetX (Count and int);   Friend function public
:
    Count (): X (0) {}
private:
    int x;
};

void SetX (Count &c,int val) {    //friend function is not a member function
    c.x=val;
}

Friend class

The Declaration
class a{public
: Friend class
    B;//friend class
};

The relationship between friends is neither symmetrical nor transitive, for example:
A is a friend of B, B is a friend of C, then you can't say A is a friend of C (do not pass), or B is a friend (asymmetric) This pointer

Each object can use a pointer called this to access its own location, and the this pointer is not part of the object itself, instead, this is passed as an implicit argument to each non-static member function of an object

This pointer uses
class test{public
:
    Test (int=0);
    void print () const;
Private:
    int x;
};

void Test::p rint () const{
    cout << x <<endl;           Implicit invocation of
    cout << this->x <<endl;     The arrows call 
    cout << (*this). x <<endl;   Dot Call
}


//Use this to achieve the concatenation of the function call
class time{public: Time
    (int=0,int=0,int=0);

    Time &sethour (int h) {hour=h; return *this;}
    Time &setminute (int m) {minute=m; return *this;}
    Time &setsecond (int c) {second=s; return *this;}
Private:
    int hour;
    int minute;
    int second;
};

int main () {time
    t;
    The concatenated function calls
    T.sethour. Setminute (a). Setsecond ();
    The Union of DOT operators is left to right, so three functions are run from left to right
}
New and delete: dynamic management of Memory

C + + allows programmers to assign and release any built-in or user-defined type-controlled memory in a program, called Dynamic memory management , with operator new and delete complete

Allocates memory space for an object, returning a pointer to the object type Time
*timeptr;
Timeptr = new Time;
Undo a dynamically allocated object and release the space
delete timeptr;

Provides initialization values at the same time as dynamically assigned
double *ptr = new double (3.14);   Base type Time

*timeptr = new Time (1,2,3);    Custom Object

//dynamically allocate array
int *array = new INT[10];
int n = 7;
int *array = new Int[n];
Frees the memory of the dynamically allocated array
delete [] array;
delete [] Array;
Static Class members

Each instance object of a class has a copy of all the data members of the class, but the static member exception, a copy of which is shared by all objects of the class, is different from the global variable, which works only in the scope of the class Static can be initialized only once by life as public, private, or protected static, and by default will be initialized to 0 (base type) except for const static data members of int or enum type. All other static members must continue beyond the class definition body to define that a static member or function of a class exists and can be used in a static member function, even if no instantiated object exists and cannot be declared as const by using the this pointer static member function

Class student{public
:
    Student (string n) {allstu++; name=n;}
    static int getstudent () {return allstu;}
Private:
    string name;
    static int allstu;  Static member data of type int can be defined within class
};
int student::allstu = 0;
    How do I call the static function
    cout<< student::getstudent () << Endl

    when an int main () {//has no instance of a class? Student *jack=new Student ("Jack");
    Student *tom=new Student ("Tom");

    Both results
    cout<< jack->getstudent () << Endl;
    cout<< tom->getstudent () << Endl;
}

Reference:c++ University Course -5th

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.