The assignment method for the c++ member variable in the c++ class

  • 2020-05-10 18:36:34
  • OfStack

1 const member variable c++ rule is defined in the class definition of the header file:

1, class definition can not be initialized, because the class definition in the header file is only a declaration, and no real space is allocated, so the variable does not exist, so it cannot be assigned.

2. The variable defined by const cannot be assigned

How do you do that? You can't assign a value in the declaration, you can't assign a value after the declaration. You have to assign.

Solutions:

1. Initialize in the parameter initialization list after the constructor

2. Initialize the const variable as static type at the same time.

Eg:


#include <iostream>

class CTestA
{

public:

CTestA():m_iSIZE(20)         // method 1
{
}

~CTestA()
{
}

int GetSize()
{
return m_iSIZE;
}

private:
const int m_iSIZE;
};

class CTestB
{
public:
CTestB()
{
}

~CTestB()
{
}

int GetSize()
{
return m_iSIZE;
}

private:
static const int m_iSIZE;
};
const int CTestB::m_iSIZE = 3;       // method 2

int main()
{
CTestA oTestA;
CTestB oTestB;

std::cout<<"oTestA:"<<oTestA.GetSize()<<std::endl<<"oTestB:"<<oTestB.GetSize()<<std::endl;
return 0;
}

Related articles: