Abstract base class created by pointer array

Points to note in the establishment of an array of pointers in the abstract base class:

This can be attributed to the point of knowledge of pointers, which is to distinguish clearly what the pointer represents when creating one-dimensional and two-dimensional arrays. Under the limitation of the scope of class, it has its unique meaning.
1. When a one-dimensional array is created, each element of the array represents data of an array type.
int *p = new int[2];

Here p[0], p[1] are both int type data.

Putting it into a class, creating a one-dimensional array of a class actually creates multiple class objects.
class Circle{
    
    
	double radius;
public:
	Circle(double r = 0) : radius(r){
    
    }
	double Area(){
    
     return 3.1415 * radius * radius;}
}
int main(){
    
    
	Circle *p = new Circle[2];
}

Here in the new pointer array, it is equivalent to creating two Circle objects, namely p[0], p[1].

2. When a two-dimensional pointer array is created, each element is essentially a pointer, just a pointer of different data types. This is equivalent to creating an array of pointers of this data type.
int **p = new int* [2];

Here p[0], p[1] are both an int *p

For classes, the creation of a two-dimensional pointer array of the class does not generate class objects (no constructor is used), only pointers to multiple classes are created.
class Circle{
    
    
	double radius;
public:
	Circle(double r = 0) : radius(r){
    
    }
	double Area(){
    
     return 3.1415 * radius * radius;}
}
int main(){
    
    
	Circle **p = new Circle* [2];
}

Here p[0], p[1] are pointers of the Circle class

3. Therefore, for abstract classes, since they cannot create class objects but can create class pointers, it is impossible to create a one-dimensional array with pointers, but it is possible to create a two-dimensional array.
class Shape{
    
    
	virtual double Area() = 0;
}

int main(){
    
    
	Shape *p = new Shape[2]; // 错误!
	Shape **p = new Shape* [2]; // 正确
}

The first will report an error, and the second will be correct. An array of abstract base class pointers can be established, and each pointer can point to a specific class object.

Guess you like

Origin blog.csdn.net/weixin_45688536/article/details/108253835