The policies of two classes in C ++

Source: Internet
Author: User

The policies of two classes in C ++
I. Problem Description
Class A contains class B instances, and Class B also contains class A instances.
 
Ii. solution strategies
 
1) solution to errors
File A contains file B, and file B contains file A, which forms an endless loop.
[Html]
# Include "B. h"
 
Class
{
Int I;
B B;
};
 
# Include "A. h"
Class B
{
Int I;
A;
};

2) correct writing and precautions
1) The main function only needs to contain B. h, because B. h contains a. h.
2) class B does not need to be included in a.h, but must be declared. B is also successfully referenced while avoiding endless loops.
3) include class B but not the header file "B. h". In this way, only pointer of type B can be declared !!!! It cannot be instantiated !!!!

 
A.h:
[Html]
# Include <iostream>
Using namespace std;
 
Class B;
 
Class
{
Public:
B * ib;
Void putA ()
{
Cout <"this is A class" <endl;
}
 
};

B .h:
[Html]
# Include <iostream>
# Include "a. h"
 
Using namespace std;
Class B
{
Public:
A ia;
Void putB ()
{
Cout <"This is B type" <endl;
}
 
};

Main Function
[Html]
# Include <stdio. h>
# Include <tchar. h>
# Include "B. h"
Int _ tmain (int argc, _ TCHAR * argv [])
{

B B;
B. putB ();
 
B. ia. putA ();
 


 
Getchar ();
Return 0;
}

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.