14. C ++-Second-Order construction mode, youyuan (details), and 14. c construction mode details

Source: Internet
Author: User

14. C ++-Second-Order construction mode, youyuan (details), and 14. c construction mode details

First, review the previously learned constructors.

  • Class constructor is used for object initialization.
  • The constructor has the same name as the class and has no returned value.
  • The constructor is automatically called during definition.

The execution result cannot be determined because the constructor does not return a value,Therefore, the initialization object cannot be successful.

For example:

class Test{private:   int *p;public:   Test(int i)   {     p=new int(i);   }}

Assume thatNew allocationIf it failsBugIf the code size is large, it is difficult to find this problem.Semi-finished objects.

 

How can we avoid the birth of semi-finished products?

It will be used in this chapterSecond-Order StructureNow.

 

Second-Order Structure

Construct a process in two steps

-Resource-independent initialization operations

Operations that are not prone to exceptions,For example:Initialize common variables such as int and flaot

-Operations that require system resources

Operations that may cause exceptions,For example:Memory application, file access, etc.

As shown in:

 

The procedure is as follows:

1. CreatePrivate ConstructorBecause the constructor does not return valuesFirst-stage construction

2. CreatePrivate function with return value, UsedConstruct the Second Stage, Returns the result of successful construction.True, Failed to returnFalse

3. CreateStatic member functionsCreate an object through new, call the functions in steps 1 and 2, and finallyProcess judgment

See the following example:

# Include <stdio. h> class TwoPhaseCons {private: TwoPhaseCons () // The first-stage constructor {} bool construct () // The second-stage constructor {return true;} public: static TwoPhaseCons * NewObj (); // object creation function}; TwoPhaseCons * TwoPhaseCons: NewObj () {TwoPhaseCons * ret = new TwoPhaseCons (); // if the second stage fails to be constructed, returns NULL if (! (Ret & ret-> construct () {delete ret; ret = NULL;} return ret;} int main () {TwoPhaseCons * obj = TwoPhaseCons :: newObj (); printf ("obj = % p \ n", obj); delete obj; return 0 ;}

  

C ++ youyuan

What is youyuan?

The C ++ classEncapsulation, OutsideInaccessibleTo classPrivatePrivate member, soYouyuanIt was born.

-The friend element of a class can be a function or another class.

For example, if the friend of the Test class is a func () function, the func () function can access any member variables (including static, private, and shared) of the Test class)

-Youyuan is convenient and convenient.

-The disadvantage of youyuan is that it destroys the object-oriented encapsulation and is gradually abandoned in modern times.

 

Youyuan definition, which is used in the classFriend keywordFor example:

Class Test {friend void f_func (const Test & t); // declare that f_func () is a friend of this class}; void f_func (const Test & t ){...... // you can access any member variables in the Test Class Object t}

 

Example 1

The Test classYouyuan (function)To access member variables, the Code is as follows:

# Include "stdio. h "class Test {private: static int n; int x; int y; public: Test (int x, int y) {this-> x = x; this-> y = y;} friend void f_func (const Test & t); // declare that the friend of Test is f_func () function}; int Test: n = 3; void f_func (const Test & t) {printf ("t. x = % d \ n ", t. x); printf ("t. y = % d \ n ", t. y); printf ("t. n = % d \ n ", t. n); // access the private static member variable} int main () {Test t1 (1, 2); f_func (t1); return 0 ;}

Run print:

t.x=1t.x=2t.x=3

Example 2

TheYouyuan (Class B)To access member variables, the Code is as follows:

# Include "stdio. h "class A {int I; int j; public: A () {I = 10; j = 20;} friend class B; // declare that the friend of A is B }; class B {public: void accesskey (const A & t) {printf ("t. I = % d \ n ", t. i); printf ("t. j = % d \ n ", t. j) ;}}; int main () {A t1; B t2; t2.accessA (t1); return 0 ;}

Run print:

t.i=10t.j=20

  

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.