/**
* @file PrjStructInCpp.cpp
* @brief show how to use struct on c++
*/
/**
* @note build on vs2005 + unicode + winxpSp3
*/
#include "stdafx.h"
#include <windows.h>
#include <locale.h>
#include <string>
#include <tchar.h>
#ifndef tstring
#ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
#endif
#ifndef WIDEN2
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFILE__ WIDEN(__FILE__)
#define __WLINE__ __LINE__
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define TRACE_CODE_INFO \
{\
tstring str = __WFUNCTION__;\
_tprintf(_T("<%s>\n<%d>\n<%s>\n"), __WFILE__, __WLINE__, str.c_str());\
}
#endif
#pragma pack(1)
typedef struct _tag_info
{
_tag_info()
{
TRACE_CODE_INFO;
init();
showMe();
}
_tag_info(INT iPosition, TCHAR * pContent)
{
TRACE_CODE_INFO;
init();
setPos(iPosition);
setContent(pContent);
showMe();
}
~_tag_info()
{
TRACE_CODE_INFO;
UnInit();
showMe();
}
void init()
{
iPosition = 0;
pContent = new TCHAR[_MAX_PATH];
ZeroMemory(pContent, _MAX_PATH * sizeof(TCHAR));
}
void UnInit()
{
if (pContent)
{
delete pContent;
pContent = NULL;
}
}
void showMe()
{
_tprintf(_T("iCount = <%d>, pContent = <%s>\n\n"), getPos(), getContent());
}
INT getPos()
{
return iPosition;
}
VOID setPos(INT iPos)
{
iPosition = iPos;
}
TCHAR * getContent()
{
return pContent ? pContent : _T("NULL");
}
VOID setContent(TCHAR * pContent)
{
_tcscpy_s(this->pContent, _MAX_PATH, pContent);
}
private:
INT iPosition;
TCHAR * pContent;
} TAG_INFO;
#pragma pack()
int _tmain(int argc, _TCHAR* argv[])
{
_tsetlocale(LC_ALL, _T("Chinese_People's Republic of China.936"));
TAG_INFO * pTagInfo = new TAG_INFO(6, _T("show how to use struct on c++"));
if (pTagInfo)
{
delete pTagInfo;
pTagInfo = NULL;
}
/** run results
// <d:\lsprj\subjectresearch\struct_in_c_plus_plus\program\mainprog\prjstructincpp\
// prjstructincpp\prjstructincpp.cpp>
// <53>
// <_tag_info::_tag_info>
// iCount = <6>, pContent = <show how to use struct on c++>
//
// <d:\lsprj\subjectresearch\struct_in_c_plus_plus\program\mainprog\prjstructincpp\
// prjstructincpp\prjstructincpp.cpp>
// <64>
// <_tag_info::~_tag_info>
// iCount = <6>, pContent = <NULL>
*/
/**
* 实验结果:
*
* 结构在c++中也是存在构造和析构函数的, 要清理结构内开辟的资源,不用手工调用
* 放在结构的析构函数中自动处理好了
*
* 在c++结构中, 成员变量也是可以使用public或private描述的,
* 成员变量也可以像类成员变量一样, 放在结构的最后面定义.
* 也可以使用getor和setor函数对成员变量的操作进行封装
*/
getchar();
return 0;
}
how to use struct on c++
最新推荐文章于 2024-05-20 21:45:34 发布