17. Object construction

If no initial value is assigned, the initial value of the member variable in the global storage area is 0 by default, and the initial value of the member variable in the stack space and heap space is a random number by default.

From a programming point of view, objects are just variables,

C++ can define a special member function-constructor with the same name as the class.

Constructors do not have any return type declaration.

Constructors are automatically called when an object is defined.

Every object should be initialized before use, the constructor is used for object initialization.

Constructors can define parameters as needed, and object definitions are different from object declarations:

Object definition: Allocate space for the object and call the constructor.

Object declaration: tells the compiler that such an object exists.

Executing program: Preprocessor -> Compiler (generates executable file) -> Linker

Test t1(1); //call Test(int v)

Test t2=1; //Call Test likewise (int v)

int i=1; //initialization

int i(100); //initialization

i=1; //assignment

Manually call the constructor:

Test ta[3]={ Test(), Test(1), Test(2) };

Test t=Test(100); // Manually call the initialization method

Small example: develop an array class to solve the security problem of native arrays

    Provide a function to get the length of the array

    Provides a function to get elements of an array

    Provides a function to set an array element

#ifndef _INTARRAY_H_
#define _INTARRAY_H_
class IntArray
{
private:
int m_length;
int* m_pointer;
public:
IntArray(int len);
int length();
bool get(int index, int& value);
bool set(int index,int value);
void free();
};

#endif

#include "IntArray.h"
IntArray::IntArray(int len)
{
m_pointer=new int[len];
for(int i=0;i<len;i++)
{
m_pointer[i]=0;
}
}
int IntArray::length()
{
return m_length;
}
bool IntArray::get(int index, int& value) 
{
bool ret=(0<=index)&&(index<length());
if(ret)
{
value=m_pointer[index];
}
return ret;
    }
bool IntArray::set(int index,int value)
{
bool ret=(0<=index)&&(index<length());
if(ret)
{
m_pointer[index]=value;
}
return ret;
}
void IntArray::free()
{
delete[] m_pointer;

}

#include <iostream>
#include "IntArray.h"
using namespace std;
int main()
{
IntArray a(5);
for(int i=0;i<a.length();i++)
{
a.set(i,i+1);
}
for(int i=0;i<a.length();i++)
{int value=0;if(a.get(i,value)){cout<<value<<endl;}}a.free();system("pause");return 0;









}


Guess you like

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