The definition and implementation of the "reprint" Learning C + + class (Classes)

Source: Internet
Author: User
Tags class definition

I. Introduction to "Class"
In C + +, use theclass"To describe"Object"The so-called" object "refers to all things in the real world. Then the class can be regarded as the abstraction of similar things, to find the similarities between these different things, such as bicycles and motorcycles, first of all they belong to the "object", and have the same point, and some different points, the same point as they have quality, there are two of wheels, all belong to transport and so on. "All have quality", "two wheels" belong to this object's properties, and "can be used as a vehicle" belongs to the behavior of the object, also known as the method.

A class is a user-defined data type, and the type of data has a certain ability to behave, that is, the method described in the class. In general, the definition of a class consists of two parts, one of which is the class'sProperties, and the other part is what it has.Method。 In the category of "human beings", each person has his or her name, age, date of birth, weight, etc., as part of human nature, in addition, people can eat, sleep, walk, talk and so on belong to human behavior.

The "Man" class described in the example above is merely the most basic attribute and behavior of a human object, which can be called human "base class"。 Besides, some people with some professions, such as students, a student also have the attributes that are not in the "base class", such as school, class, student number; You can also have behaviors that the base class does not have, such as needing to go to class every day, exams, etc.

The student class can be seen as an extension of the base class, because he has all the properties and behaviors of the base class, and on that basis adds properties and behaviors that the base classes do not have, and classes like "students" are called "human" as the base class.Derived ClassesOrsub-class"。 In the student base Shanghai can further expand the other more advanced classes, such as the "postgraduate" category.

In this way, we no longer have a deeper introduction to other relevant knowledge of the class.

Ii. definition of C + + class
C + + uses the keyword class to define a class with the following basic form:

    Class name    {            public://Common behavior or attribute        private:            //Public behavior or property    };

   Description:
①. Class names need to follow the general naming conventions;

Ii. PublicAndPrivateFor the attribute/method limit of the keyword, private means that the part of the content is private, cannot be accessed or invoked externally, can only be accessed within this class; Public represents the properties and methods that are exposed and can be accessed or invoked directly by the outside world.
In general, the property members of the class should be set to private, public only to those used by the outside to invoke the function interface, but this is not mandatory, can be adjusted as necessary;

③. The semicolon of the ending section cannot be omitted.


example of a class definition:
Defines a point class that has the following properties and methods:
Properties: x-coordinate, y-coordinate
Method: 1. Set the coordinate value of x, y; 2. Output coordinate information.

The implementation code is as follows:

            Class Point            {public                :                    void setpoint (int x, int y);                    void Printpoint ();                Private:                    int xPos;                    int yPos;            };

  

   Code Description:
         A class named point is defined in the previous section of code with two private properties. The xpos and ypos of int are used to denote X-and Y-points respectively. On the method,   setpoint   used to set properties, i.e. XPos and yPos values;   Printpoint   The information used to output the point.
        
         classes are defined with the following points to note:
            ①. The data members of the   class cannot be decorated with auto, extern, and register, and cannot be initialized at definition, such as   int xPos = 0; //error ;
            ②. The order and number of occurrences of the private and public keywords can be arbitrary when the   class is defined;
            ③.   At the end of the semicolon can not be omitted, remember!
            
            



Third, C + + class implementation
In the above definition example, we just define some properties and method declarations of this class, and do not implement it, the implementation of the class is the process of completing its method. Classes are implemented in two ways, one is to complete the definition of a member function when the class is defined, and the other is done outside the class definition.

1>. Defining member functions when a class is defined
The implementation of member functions can be done at the same time as the class definition, such as code:

#include <iostream>        using namespace std;        Class Point        {public            :                void setpoint (int x, int y)//implement SetPoint function                {                    xPos = x;                    YPos = y;                }                void Printpoint ()       //Implement Printpoint function                {                    cout<< "x =" << xPos << Endl;                    cout<< "y =" << yPos << Endl;                }            Private:                int xPos;                int yPos;        };        int main ()        {point            M;        Create an object point with a defined class M            m.setpoint (10, 20);//Set the X, Y value of the M point            m.printpoint ();     Output m-point information            return 0;        }

Implementing a member function within a class is no longer declared within a class, but rather directly defined by a function, and when a member function is defined in a class, the compiler will seek to define it as an inline function by default.

2>. Defining member functions outside of a class
Defining a member function outside of a class is done by declaring it within a class and then passing outside the class through the scope operator: : To do this, in the form of:

        return type class Name:: member function name (argument list)        {            //function Body        }

Replace the code in the example with the code for the out-of-class definition member function:

 #include <iostream> using namespace std; Class Point {public:void setpoint (int x, int y);//Declaration of member functions within a class void PRI            Ntpoint ();                Private:int XPos;        int YPos;        };            void Point::setpoint (int x, int y)//through the scope operator ':: ' to implement the SetPoint function {xPos = x;        YPos = y; } void Point::p rintpoint ()//implement Printpoint function {cout<< "x =" << xPos << en            dl        cout<< "y =" << yPos << Endl;        } int main () {point M; Create an object point with a well-defined class M M.setpoint (10, 20);     Sets the X, Y value of the M point M.printpoint ();        Output m-point information return 0; }

In the case of the SetPoint member function, the form declared in the class is void SetPoint (int x, int y) , then the function header should be void point::setpoint (int x, int y) when defined outside the class in this form, the return type, member function name, and parameter list are identical to those declared within the class.

Iv. use of C + + classes
Once a class is defined and implemented, it is possible to create objects with this class, as simple as declaring a variable as a basic data type such as int, char, for example, we have a point class, and the object to create a point requires only:

        The name of the point object;

The object that creates a class is called the instantiation of the class, and when it is created, we can also initialize the properties of the object so that the object has a certain property after it is created, which will be learned in the next post.
After instantiating a class, the system allocates a certain amount of storage space based on the actual needs of the object. This allows you to use the object to access or invoke the properties or methods that the object can provide.

Also take the above code as an example, in order to reduce space, we put the implementation of the point class in the Point.h header file, where the implementation code of the point class is no longer posted.

 #include <iostream> #include "Point.h" using namespace std;        int main () {point M;         Create an object point with a well-defined class M M.setpoint (10, 20);             Sets the X, Y value of the M point M.printpoint ();       Output M-point information cout<< m.xpos <<endl;    Attempt to access the property via Object M xpos return 0; }

The code will compile with an error that says: ' int point::xpos ' is private, which is cout<< m.xpos <<endl; This line caused, he tried to access a Private data in private objects XPos, if this line is removed, it will work.

By the name of the object. Public Function name (parameter list) , the form of which can call the method that the class object has, through the object name. A public data member , which can access the data members in the object.
v. Scope of object, visible domain and life cycle
Class objects are scoped, visible, and have the same lifetime as normal variables, and when objects are automatically revoked at the end of the object's lifetime, the memory used is recycled, and it is important to note that if the object has a member function that uses new or malloc The requested dynamic memory program does not release it and requires us to clean it manually, otherwise it will cause a memory leak.

The definition and implementation of the "reprint" Learning C + + 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.