Simple C ++ object-oriented

First, the three characteristics of object-oriented

    Three properties: encapsulation, inheritance, polymorphism

  • Package: a package object-oriented programming is to achieve the first step, the package is a collection of a number of units (called class) data or functions and the like. The significance of packaging is to protect or prevent the codes (data) we are inadvertently destroyed.
  • Inheritance: Inheritance main reuse of code, saving development time. Subclasses can inherit something the parent class.
  • Polymorphism: the same operation applied to different objects can have different interpretations, produce different execution result. Multi-state and multi-state operation when divided compilation.

Second, a detailed understanding

(1) Package

    Can understand that the first step towards object-oriented programming. So what we need to package it? The following is a specific explanation.

The package is obtained abstracted data and behavior (or function) combine to form an organic whole, that is, the source data and operational data organically combined to form a "class", which is a class of data and functions member. The purpose of the package is to enhance security and simplify programming, the user need not know the specific implementation details, but just want to use members of the class through an external interface, a specific access rights.

    As can be seen from the above classes have attributes and behavior. Here is a simple column: Xiao Ming to eat, walk red, Xiaogang sleep. According to these simple cases, we can abstract the name of the property, eating, walking, sleeping these acts. Further encapsulation class.

class People
{
public:
	string strName;

public:
	void Walk()	{ cout << strName << "正在走路" << endl; }
	void Eat() { cout << strName << "正在吃饭" << endl; }
	void Sleep() { cout << strName << "正在睡觉" << endl; }

};

    Now talking about the class, we will help novice programmer to talk to the class using https://www.runoob.com/cplusplus/cpp-classes-objects.html .

1. Class

    Speaking before a class with properties and behavior, we use the example of a novice programmer to write a Box class.

class Box
{
	//属性
public:
	double m_dLength;
	double m_dWidth;
	double m_dHeight;

	//方法
public:
	//返回体积
	double m_getVolume(void) { return m_dLength * m_dWidth * m_dHeight;  }

};

    Next we embody, producing an object according to the actual situation, calling its methods.

int main()
{
	//比方: 现在有一个水池, 长20 宽10 深5 , 要求出它的最大蓄水量
	//我们就可以根据上面抽象出的类, 进行操作了
	//1. 先生存一个对象
	Box BoxPool;

	//2. 具体化它的属性
	BoxPool.m_dLength = 20;
	BoxPool.m_dWidth =  10;
	BoxPool.m_dHeight =  5;

	//3. 调用它的方法体积,就可以求出结果了
	cout << BoxPool.m_getVolume() << endl;

}

//输出:	1000

2. Class access modifiers

    Talked about this, public might appear above doubt. Here we will have to reconsider the object-oriented.

The data package is an important feature of object-oriented programming, which prevents direct access to the internal member function of class type. Access is restricted by the members of the respective regions marked public, private, protected inside the class specified in the body. Keywords public, private, protected access modifier called.

  • Public: public members outside the class program is accessible. You can not use any member functions to set and get the value of public variable.
  • Private: private member variables or functions outside the class is not accessible, even impossible to see. Only classes and friend functions can access private members. By default, all members of the class are private.
  • Protected: protected member variables or functions with private members are very similar, with one exception, to protect members of the derived class (ie subclasses) it is accessible.

    Continued speaking on the example, if the data provider, do not want to let people know the depth of their home pool, we how to operate it?

class Box
{
	//属性
public:
	double m_dLength;
	double m_dWidth;

private:
	double m_dHeight;

	//方法
public:
	//返回体积
	double m_getVolume(void) { return m_dLength * m_dWidth * m_dHeight;  }

};

    As long as the class to access the pool depth attribute modifiers changed Privated can, try to access it. Obviously wrong, this time we do not even have an assignment, and how to do it?

Here Insert Picture Description
    Class access modifier particular use, the following example will be described.

3. Constructor

    For the above, we can write methods within the class assignment of a Public, private, after all, just can not be accessed outside the class, we can access private members in a class by this method.

class Box
{
	//属性
public:
	double m_dLength;
	double m_dWidth;

private:
	double m_dHeight;

	//方法
public:
	//返回体积
	double m_getVolume(void) { return m_dLength * m_dWidth * m_dHeight; };
	void m_setLength(double dHeight) { m_dHeight = dHeight; };
};


int main()
{
	//比方: 现在有一个水池, 长20 宽10 深5 , 要求出它的最大蓄水量
	//我们就可以根据上面抽象出的类, 进行操作了
	//1. 先生存一个对象
	Box BoxPool;

	//2. 具体化它的属性
	BoxPool.m_dLength = 20;
	BoxPool.m_dWidth =  10;
	BoxPool.m_setLength(5);

	//3. 调用它的方法体积,就可以求出结果了
	cout << BoxPool.m_getVolume() << endl;

}

    Mo was a problem, the program perfectly executed.

    Single assignment after all, is too cumbersome, but also take into account whether the property is private. So this time we use the constructor to initialize.

Class constructor is a special member function, it executes each time a new object class creation. Name The name of the class constructor is identical, and will not return any type, it does not return void. Constructor is used to set the initial values for certain member variable.
When the class created will call the constructor. But sometimes do not write your own constructor, then the system will call the default constructor (ie do nothing)
but when writing a constructor, the system will not call the default constructor

class Box
{
	// 系统默认产生的啥都不做的构造函数,这个显式的注释出来了。
	//Box() {};
public:
	Box(double dLength, double dWidth, double dHeight) : m_dLength(dLength), m_dWidth(dWidth), m_dHeight(dHeight) {};
	//属性
public:
	double m_dLength;
	double m_dWidth;

private:
	double m_dHeight;
	//方法
public:
	//返回体积
	double m_getVolume(void) { return m_dLength * m_dWidth * m_dHeight; };
	void m_setLength(double dHeight) { m_dHeight = dHeight; };
};

    Produce an object, try to run down the results.

int main()
{
	Box BoxPool(20, 10, 5);

	cout << BoxPool.m_getVolume() << endl;

}

//输出:	1000

    Talk to the constructor, then it's best CP destructor would have to talk about the whole thing.

4. destructor

Class destructor is a special class member function, it executes each time the object is created deleted.
The class name as the destructor is identical, only preceded by a tilde (~) as a prefix, it does not return any value, it can not have any parameters. Destructor helps exits the routine (such as closing the file, the release of memory, etc.) prior to the release of resources.

    Here is an explanation about the destructor https://blog.csdn.net/weizhee/article/details/562833 , the destructor is still very important to drop.

(2) inheritance

    Inherit the literal meaning can know who is who inherited the meaning, then there is a body and successor. In object-oriented, we become the subject for the base class, the successor to the derived class. Derived class's base class has it all. Public inheritance, inheritance and protection of private inheritance, personal understanding is that the inherited property (that is, what they do not) change their access level, public lowest level, nothing changed; protected, change the base class for the public protected, private unchanged; private, change all private.

Another class inheritance allows us to define a class basis, which makes creating and maintaining an application easier. In doing so, also reached the reuse of code functionality and improve the efficiency of the effect. When you create a class, you do not need to re-write new data members and member functions, simply specify the new class inherits members to an existing class. The existing class is called the base class, the new class is called the derived class.

    Public inheritance, protection of inheritance, private inheritance can explain in detail see here https://www.cnblogs.com/weiyouqing/p/9648563.html

    Here, give a public inheritance example for understanding the inheritance of it, the code is taken from the rookie tutorial .

#include <iostream>

using namespace std;

// 基类: 形状
class Shape
{
protected:
	int m_nWidth;
	int m_nHeight;

public:
	void m_setWidth(int nWidth) { m_nWidth = nWidth; };
	void m_setHeight(int nHeight) { m_nHeight = nHeight; };
};

// 派生类: 长方体
class Rectangle : public Shape
{

public:
	int getArea() { return m_nHeight * m_nWidth; };
};


int main()
{
	Rectangle Rect;

	Rect.m_setWidth(5);
	Rect.m_setHeight(7);

	// 输出对象的面积
	cout << "Total area: " << Rect.getArea() << endl;

}

//输出:	Total area: 35

    Reality children will inherit the faces are some of the features of father and mother. In succession, this is called multiple inheritance .

Multiple inheritance that is a subclass can have more than one parent class that inherits the characteristics of more than one parent class.

#include <iostream>
 
using namespace std;
 
// 基类 Shape
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};
 
// 基类 PaintCost
class PaintCost 
{
   public:
      int getCost(int area)
      {
         return area * 70;
      }
};
 
// 派生类
class Rectangle: public Shape, public PaintCost
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};
 
int main(void)
{
   Rectangle Rect;
   int area;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
 
   area = Rect.getArea();
   
   // 输出对象的面积
   cout << "Total area: " << Rect.getArea() << endl;
 
   // 输出总花费
   cout << "Total paint cost: $" << Rect.getCost(area) << endl;
 
   return 0;
}

// 输出: Total area: 35
//		 Total paint cost: $2450

    Understand the above inheritance, we may submit such a question, if the base class has a car, have the same subclass of a car, then how to distinguish it?

(3) Polymorphism

Polymorphism literally means that a variety of forms. When there is a hierarchy between classes, and inheritance between classes through the association will be used polymorphism. When C ++ member function calls polymorphic means that will perform different functions depending on the type of the object function is called.

#include <iostream>

using namespace std;

class  A
{
public:
	void Show() { cout << "A::Show" << endl; };

};

class B : public A
{
public:
	void Show() { cout << "B::Show" << endl; };

};

class C : public A
{

public:
	void Show() { cout << "C::Show" << endl; };

};


int main(void)
{
	B b;
	b.Show();

	C c;
	c.Show();

	A* a = &b;
	a->Show();

	a = &c;
	a->Show();
}

/*
输出:
B::Show
C::Show
A::Show
A::Show
*/

    The above is an obvious example of polymorphism, but why even a A :: Show output it. Because a static type is A *, a function call before the program is ready to perform. This is also sometimes referred to as early binding. And b, c are all static and dynamic type B, C.
Here Insert Picture Description

Static binding and dynamic binding in C ++: https://www.cnblogs.com/lizhenghn/p/3657717.html

    So how to change it? This time to introduce a noun: virtual function

1. virtual function

Virtual function is declared virtual function using the keyword in the base class. When redefine the base class virtual function defined in a derived class, it tells the compiler not statically linked to the function.
What we want is any point in the program can be selected according to the type of object function calls invoked, this operation is called dynamic linking, or late binding.

    The above example can be changed to:

class  A
{
public:
	virtual void Show() { cout << "A::Show" << endl; };

};

/*
输出:
B::Show
C::Show
B::Show
C::Show
*/

Here Insert Picture Description
    Reality, we will peacocks, tigers, lions and other animals as abstract base class, specific animal is a derived class. Obviously, the derived class can be instantiated as specific things, but if the base class - animal instantiation is obviously unreasonable. This time we need to introduce a pure virtual function, to tell the user can not be instantiated.

2. pure virtual function

Pure virtual function is declared in the base class virtual function, it is not defined in the base class, but requires that any derived class must define your own implementation. A method to achieve pure virtual function in the base class is added after the function prototype "= 0." It declares a pure virtual function of the class is an abstract class. Therefore, the user can not create an instance of the class, it can only create an instance of the derived class. So pure virtual function declaration class is a subclass of the designer told, "You must provide an implementation of pure virtual functions, but I do not know how you will achieve it."

And the difference between virtual function pure virtual function: https://blog.csdn.net/Hackbuteer1/article/details/7558868

#include <iostream>
#include <cstdlib>
#include <cstdio>

using namespace std;


class abstractcls
{
public:
	abstractcls(float speed, int total)   //构造函数
	{
		this->speed = speed;
		this->total = total;
	}

	virtual void showmember() = 0;    //纯虚函数的定义
protected:
	float speed;
	int total;
};

class car : public abstractcls
{
public:
	car(int aird, float speed, int total) :abstractcls(speed, total)
	{
		this->aird = aird;
	}

	virtual void showmember()
	{
		cout << speed << "--------" << total << "-----------" << aird << endl;
	}
protected:
	int aird;
};
int main()
{
	car b(250, 150, 4);
	b.showmember();
	return 0;
}

/*
输出:
150--------4-----------250
*/
Published 25 original articles · won praise 7 · views 2137

Guess you like

Origin blog.csdn.net/qq_41506111/article/details/102823615