Header file and class declaration

    When we start to learn C++, we should develop standardized programming habits, and the layout of header files is one of the most important points. We need to know about defensive declarations in header files.
#ifndef __COMPLEX__
#define __COMPLEX__
//forward declarations
#include<cmath>

class ostream;
class complex;

complex& __doapl (complex* ths, const complex& r);
//class-declarations (class-declarations)
class complex
{
   ...
};
//class-definition (class-definition)
complex::function ...

#endif

    In the class declaration section, we take a look at what the format of the specification looks like, which can lay the foundation for our future programming style.

class complex
{
public:
  complex (double r = 0, double i = 0)
    : re (r), im(i)
  { }
  complex& operator += (const complex&);
  double real () const {return re;}
  double imag () const {return im;}
private:
  double re, im;

  friend complex& __doapl (complex*, const complex&);
};

    The class declaration includes two parts: class head and class body. Some functions are defined directly in the body, such as real() and imag() here, and some are defined outside the body.

    Templates are also very important in C++. If we don't want to write the data type double, it is very inconvenient for us to modify. We can use templates.

template<typename T>
class complex
{
public:
  complex (T r = 0, T i = 0)
    : re (r), im (i)
  { }
  complex& operator += (const complex&);
  T real () const {return re;}
  T imag () const {return im;}
private:
  T re, im;

  friend complex& __doapl (complex*, const complex&);
};

    The inline function in C++ can replace the macro definition in the form of an expression. If the function is defined in the class body, it will automatically become an inline candidate without adding the inline keyword. However, you need to add inline decoration before defining functions outside the class. Inline is just a suggestion to the compiler, and the compiler can choose to ignore this suggestion. For example, if a function with more than 1000 lines is specified as inline, the compiler will ignore the inline and restore the function to a normal function. We need to know that an inline function inserts the object code of the function at compile time into every place where the function is called.

    There are three types of access levels: public, private and protected. We generally put functions in the public area and data in the private area. Access levels can be interleaved.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325891882&siteId=291194637