[C ++ syntax] class

Source: Internet
Author: User
What is a class?

Class is the basis of object-oriented. C contains no objects, only data, that is, static dead objects.

From the process-oriented upgrade to the object-oriented architecture, an object is a dynamic and dynamic combination of data and methods.

Class represents the characteristics of a class of things. Objects are class-specific and instantiated.

Class declaration and definition

In general, the class declaration is in the corresponding header file, and the class definition is in the corresponding source file. In this way, the interface and implementation are separated.

// Dog. h # ifndef _ dog_h _ # DEFINE _ dog_h _ # include <string >#include <iostream> class dog {// class Declaration public: // Public Member dog () {}// default constructor dog (float weight): weight (weight) {// implicit conversion of sex = true;} explicit dog (bool ismale): Sex (ismale) {}// explicit modifier cannot be implicitly converted to dog (float weight, bool sex); dog (const Dog & dog): weight (dog. weight), sex (dog. sex), name (dog. name), power (dog. power) {}; // copy the constructor Dog & operator = (const Dog & Dog) {// value assignment function Weight = dog. weight; Sex = dog. Sex ;}~ Dog () {// destructor} void Bellow (); inline STD: String tostring (); // class defines the external inline method, the method definition must be defined in the same file float getweight () const {// method defined in the class definition. The default value is inlinereturn weight;} void Info (STD :: ostream & out); static int getnum () {// return num;} // int T1 = 1; // error. The member variables in the class definition cannot be initialized. Const static int t2 = 3; // only the const static type can be initialized in the class definition. Static int T3; // initialize the static member variable in the source file. Protected: // protect the private: // Private member float weight; bool sex; mutable int power; // mutable type variable, which can still be modified in the const object. STD: string name; static int num; // static member variable}; STD: String dog: tostring () {// class defines the external inline method, the method definition must be in the same file as the class definition: STD: String STR ("Dog [name ="); STR + = Name; STR + = ", Weight = "; STR + = weight; STR + = ", sex ="; STR + = sex; STR + = "]"; return STR ;}# endif

// Dog. CPP # include "dog. H "# include <iostream> void dog: Bellow () {// class method definition STD: cout <" Wang "<STD: Endl ;} void dog: Info (STD: ostream & out) {out <"Dog [name =" <name <", Weight =" <weight <", sex = "<sex <"] "<STD: Endl;} // const int dog: T2; // const static member definition. Int dog: T3 = 10; // initialize the static member.
Class instantiation

DOG d (1.0f );

Dog * D2 = new dog (1.0f );

Class initialization: Constructor

When a class object is created, the constructor is called.

For example:

Statement DOG d (1.0f );

Dog * D2 = new dog (1.0f );

Will make the compiler call dog (float W): weight (W) {} to initialize the object

The constructor is divided into three parts: function signature (function name and parameter list), that is
Dog (float W)

The part between the colon and braces in the initialization list is the initialization list. That is
Weight (W)

Constructor is the content in braces.

Execute the initialization list before executing the constructor.

First, execute the initialization list:

The task in the initialization list is the member variable in the initialization class. The sequence is initialized in the order declared in the class.

Class type members must be initialized at the beginning. In the initialization list, use the initialization method in the initialization list. If it is not in the initialization list, the default constructor of the class is called. It can be seen from this that there is no default constructor class type, reference type, the const type must be in the initialization list.

The built-in and composite types are not necessarily initialized. If you are initializing the list, use the initialization method in the initialization list. If not, you must check the object location, global initialization, and local initialization.

Then execute the constructor.

//playdog.cpp#include <iostream>#include <cstdlib>#include "Dog.h"Dog gloabDog;int main(){Dog localDog;gloabDog.info(std::cout);localDog.info(std::cout);return EXIT_SUCCESS;}

Output:

As a result, we can see that when the object is a local variable, the built-in type class members that do not appear in the corresponding initialization list are not initialized.

Copy constructor and value assignment function

A copy constructor is a special constructor. It has only one parameter, and the reference of the same class object.

The value assignment function assigns objects of the same type to an object.

Dog (const Dog & dog): weight (dog. weight), sex (dog. sex), name (dog. name), power (dog. power) {}; // copy the constructor Dog & operator = (const Dog & dog) {// value assignment function Weight = dog. weight; Sex = dog. sex ;}

Dog D1; dog D2 (D1); // call the copy constructor dog D3 = D1; // call the copy constructor dog D4; D4 = D1; // call the value assignment function

Assign value constructor. If you do not write a value, the compiler defaults to one. By default, member variables are copied one by one in the declared order.

 

Where the replication constructor appears:

1. The above shows the call.

2. The object is passed in as a method parameter, and the object is returned as a method return value.

3. initialize the container

4. initialize array elements

Dog D2 (D1); // display call STD: String caculate (STD: String str1, STD: String str2); // form parameter, return value STD :: vector <STD: String> SVEC (5); // first call the default constructor of string to generate a temporary String object, and then call the 5 copy constructor to initialize the container STD :: string [] STRs = {// display the temporary object generated by calling the constructor, and then calling the copy constructor to initialize the array elements string ("hello"), string ("word ")}
Destructor

Destructor are called when an object is deleted and used to release the resources occupied by the object. Whether or not a destructor is written, the compiler defaults to a destructor. The default destructor is to release resources in reverse order according to the Declaration Order of member variables. If it is of the class type, the destructor of the object is called.

When calling the destructor, you must first call the ones written by the user and then call the default ones of the compiler.

Rule 3

When should I write the copy constructor, assign value function, and destructor?

Generally, a class contains pointer member variables or resources that require special control. These three functions must be written at the same time or not at the same time.
Static Member

Class. Static members belong to a class and do not belong to any object.

Therefore, this cannot be used in the static method, and non-static methods and non-static variables cannot be accessed.

Static member variables are initialized when the class is defined. It is defined in the class definition and initialized in the class method implementation source file.

In C ++ primer, the const static member declares initialization in the class definition, but it must also be initialized empty in the class implementation source file.

For example, in the class definition, const static int t2 = 3; but the const int t2 must also be in dog. cpp;

But on my machine, it is still okay to leave this sentence in dog. cpp.

Static member call

int main(){std::cout << Dog::t3 << std::endl;std::cout << Dog::t2 << std::endl;return EXIT_SUCCESS;}

Class Encapsulation

This is implemented by the member access specifier.

Public.

Private is only accessible to this class

Protected cannot be accessed outside the class (this is similar to a private member), but it can be accessed by the member functions of the derived class.

Default Inline Function

Inline indicates the inline function in C ++. When a program calls these member functions, it does not actually execute the function call process (such as retaining the return address), but embeds the function code into the call point of the program. This greatly reduces the time overhead of calling a member function.

C ++ requires that the keyword inline be used for general inline functions, but inline can be omitted for member functions defined in the class, because these class-defined member functions have been implicitly specified as inline functions.

For example, float getweight () const is an inline function by default.

Inline functions not defined in the class definition must be defined in the same file of the class definition.

For example, inline STD: String tostring (); must also be defined in dog. H. If defined in dog. cpp, a compilation error occurs.

Implicit conversion of Constructors

Only one constructor can participate in implicit conversion.

For example, the constructor dog (float weight)

DOG d = 1.0f;

The compiler will implicitly convert the float type 1.0f to a temporary dog type object through dog (float weight), and then assign it to D.

The explicit it modifier constructor can disable implicit conversion.

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.