_c++_primer_plus_chap10_
_ See a good blog to introduce this, but I still take a bit of notes as a deeper impression of it _
Linker:_bloger_wid_ Learning C + + constructors and destructors _
1. What is a constructor function?
A constructor is a special method that is used primarily to initialize an object's members when they are created.
The meaning of its existence, to facilitate the initialization of the assignment, to avoid another function to do this thing.
→ The difference between constructors and other methods:
1. The constructor must be named exactly the same as the class name, and the generic method cannot be the same as the class name.
2. The function of the constructor is primarily used to define the state of the initialization at the time the object of the class is created. It has no return value and cannot be decorated with void. This ensures that not only does it have to be returned automatically, but there is no choice at all. The other methods have return values. Even if the return value is void, Although the method body itself does not automatically return anything, it can still be returned with something that may be unsafe.
3. The constructor cannot be called directly, it must be called automatically by the new operator when the object is created, and the general method is called when the program executes to it.
4. Automatically executes when an object is created.
2. A simple example
1#include <iostream>2#include <string>3 4 using namespacestd;5 6 classAnime7 {8 9 Public:TenAnime ()//A constructor that initializes the private variable name1,name2, the same as the class name. One { Aname1="Akashi"; -Name2="Kuroko"; - } the voidprint () - { -cout<<"The most :"<<name1<<'\ n' -<<"No.2:"<<name2<<'\ n'; + } - + Private: A stringname1; at stringname2; - - }; - - intMain () - { in - anime basketball; to basketball.print (); + - return 0; the *}
Operation Result:
Constructors can be called explicitly and implicitly.
→ What is explicit invocation and implicit invocation?
... Probably a little impression, but did not find a half-day to explain the white explanation, the first temporary.
>>not_end
C + + classes (2)