Organization of C ++ dependency header files

Source: Internet
Author: User

The following describes how to organize header files when two classes contain each other using C ++.

For example, if Cat is a class and dog is a class, cat must have a member variable.

 dog* doggy

Dog has member variables

 cat* catty

In fact, four files can be handled:

//cat.h#pragma onceclass dog;class cat{    public:        dog *doggy;        dog* getDoggy();}; //dog.h#pragma onceclass cat;class dog{    public:        cat *catty;        cat* getCatty();}; //cat.cpp#include "cat.h"#include "dog.h"dog* cat::getDoggy(){    doggy = new dog();    return doggy;} //dog.cpp#include "dog.h"cat* dog::getCatty(){    return catty;}

Principles of header file organization:

  1. Non-template class declarations and definitions are separated. Put the Declaration in. H, and put the definition in. cpp;
  2. Prevent repeated header files. There are two methods, one is
 #pragma once

The other is

 #ifndef...#define...#endif

3. Use Forward Declaration instead of # include as much as possible when the custom header files are interdependent. For example, in cat. H above

 class dog;

Change

#include "dog.h"

It is also compiled. However, if the method is also changed in dog. H, it will fail. This problem is not solved with the forward statement.

At this time, the header file organization does not conflict with the above type, and the. cpp file can be used only.

Note. Cat. cpp must contain dog. H because the constructors of the Dog class are called.

References:

Http://blog.csdn.net/lainegates/article/details/7696176

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.