众所周知,有很多方法可以访问班级成员,我现在的问题是。如果类构造函数/解构函数是公共的,则允许“新”使用以及“外部”,如果它是私有的,我可以只创建不允许“新”使用的“GetInstance”类,这对类有好处应该只有 1 个指向它们的实例(例如计算当前登录用户的服务器),并且“新”适用于指向许多对象的类(例如指向新对象的类,例如新玩家登录 int,它会创建一个指向他们每个人的新指针),并且地图将存储一个指向该对象的“新”的指针。问题是,不应该允许“extern”从全局对象私有构造函数访问吗?自从“新” 不允许使用?看看下面的例子:
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;
//CMover.h-------------------------------------
#define MAX_MOVER_NAME 32
class CMover
{
private:
BOOL m_bInitialized;
BOOL m_bIsWalking;
unsigned m_uMetersPercused;
TCHAR m_szName[MAX_MOVER_NAME+1];
//CMover( LPCTSTR szMoverName, BOOL bInitialized = TRUE, BOOL bWalking = TRUE, unsigned uMeters = 0 );
public:
CMover() { };
virtual ~CMover(){};
};
//---------------------------------------------
//CMover.cpp---------------
CMover g_Mover; //CMover was created in order to have many 'new' usage, so each 'new' object points to a new player
// Making a global object of it is a big failure
//---------------------------
//CServer.h---------------
class CConnectedUsers
{
private:
CConnectedUsers() {}; //ok, new cannot access, this class should be used as 1 object only
virtual ~CConnectedUsers() {}; //to count up connected users, 'new' should never be used
public:
map<u_long,CMover*>m_UserMng;
//I Could use GetInstance, that any pointers craeted (CConnectedUsers *pCUser = CConnectedUsers::GetInstance() ) would
//point to it
static CConnectedUsers* GetInstance( void )
{
static CConnectedUsers mObj;
return &mObj;
}
};
//------------------------
//CServer.cpp ------
//Or in this case i would like to make a global object, so on CWhatever.cpp that included CServer.h i could use
//(extern CConnectedUsers g_Users;) which is also 1 object-only so no GetInstance would be needed and I would use
//(g_Users.m_UserMng...) directly after external declared
//PROBLEM is, making constructor private regulates the class to be 1 object only, but it doesn't allow external usage
//why is that???
CConnectedUsers g_Users;
//-----------------
//Main.cpp ...etcc
int main( int argc, char *argv[] )
{
CMover *pMover = new CMover;
cout << pMover << endl << &pMover << endl; //points to a new object, pointer stored in a region
CMover *pMov2 = new CMover;
cout << pMov2 << endl << &pMov2 << endl << endl; //points to a new object, pointer stored in another region
CConnectedUsers *pCUser = CConnectedUsers::GetInstance();
CConnectedUsers *pCUser2 = CConnectedUsers::GetInstance();
cout << pCUser << endl << &pCUser << endl; //points to CConnectedUsers, pointer stored in a region
cout << pCUser2 << endl << &pCUser2 << endl; //points to same CConnectedUsers, pointer stored in another region
//also another question is, do I need to check these pointers integrity by doing:
if( pCUser )
{
//??
}
system("pause>nul");
return EXIT_SUCCESS;
}