我目前正在学习C++,这次我在搞指针,研究this
指针和多态。我的问题是,下面的转换是否安全,我知道基本上我可以m_uConnectedUsers
从CUser
课堂上直接访问,因为“公共”,但我可能会找到需要它的场合,我想知道你们专业人士的意见它。
#include <windows.h>
#include <iostream>
using namespace std;
class CUserCounter
{
public:
CUserCounter();
virtual ~CUserCounter(){};
BOOL m_bEmpty;
u_long m_uConnectedUsers;
};
CUserCounter::CUserCounter()
{
m_bEmpty = TRUE;
m_uConnectedUsers = 0;
}
class CUser : public CUserCounter
{
public:
CUser(LPCTSTR szName, BOOL bConnected, BOOL bChatting = FALSE );
virtual ~CUser(){};
BOOL m_bConnected;
BOOL m_bIsChatting;
TCHAR szCharName[32];
bool IncreaseMoverMeter( unsigned uMeters );
};
CUser::CUser( LPCTSTR szName, BOOL bConnected, BOOL bChatting )
{
if( szName )
{
if( strlen( szName ) > 30 )
strcpy( szCharName, "Invalid" );
else
strcpy( szCharName, szName );
}
m_bConnected = bConnected;
m_bIsChatting = bChatting;
}
bool CUser::IncreaseMoverMeter( unsigned uMeters )
{
//is it safe? how does it works
CUserCounter* pUserCounter = (CUserCounter*)this;
if( pUserCounter )
{
pUserCounter->m_uConnectedUsers++;
return true;
}
return false;
}
int main( int argc, char *argv[] )
{
CUser *pUser = new CUser( "Jonh", FALSE );
std::cout << pUser->IncreaseMoverMeter( 4 );
system("pause>nul");
return EXIT_SUCCESS;
}