Data members in the C ++ class have three access permissions: public, protect, and private. Private indicates that the class is private, and direct access to other classes is not allowed. protected indicates that the class itself and its children and grandchildren can access it, and direct access to other ethnic classes is not allowed, we can compare it to the common wealth of our family. public indicates that it is made public to the whole society and can be accessed directly by any class.
Generally, for the encapsulation of data members, we usually set the data members to the access permissions of protect and private. However, I recently discovered that it is also necessary to set the data members of some classes to public access permissions. So when will some data members of the class be set to public access?
We know that there are two forms of code reuse in C ++: one is inheritance by class, and the other is combination by class. The combination of classes is that the data member type of a class object is the type of another class object. The sample code is as follows:
View plaincopy to clipboardprint?
Class B
{
};
Class
{
Public:
B m_Data; // here or B * m_pData
};
Class B
{
};
Class
{
Public:
B m_Data; // here or B * m_pData
};
In this case, I tend to set m_Data, A data member of Class A, to public access. Of course, A method for getting data B in Class A can also achieve the above effect. The Code is as follows:
View plaincopy to clipboardprint?
Class B
{
};
Class
{
Public:
B & GetB ()
{
Return m_Data;
}
Protected:
B m_Data; // here or B * m_pData
};
Class B
{
};
Class
{
Public:
B & GetB ()
{
Return m_Data;
}
Protected:
B m_Data; // here or B * m_pData
};
However, I think this writing method is not as good as the first one. The first reason is that it is not elegant enough. To set the value of B, we have to add a SetB method to form the "VB style" C ++ code that my colleagues call. The second reason is that the combination of these types mainly involves the reuse of interfaces. encapsulation of class data mainly prevents the arbitrary modification of class data, however, developers have a composite type (such as the class type or struct type) for the class) I think it is less likely to modify data members at Will (compared with simple data members such as int and float ). In this way, it is easier to directly set m_Data as public access permission for external use.
This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/clever101/archive/2010/09/18/5892495.aspx