c++奇怪的搞法汇总

本文探讨了C++中静态局部变量的应用、预编译宏定义的使用限制、安全删除内存的方法、成员变量初始化的问题以及类型转换的实践案例。通过具体代码示例介绍了如何正确地运用这些特性。

1 静态局部变量

int WorkEvent::GenerateId()

{
    static int uiEventId = 0;
    return uiEventId++;

}


2 define and enum  预编译是顺序的,不能随便调整

#define MAKE_UNION(VAR) VAR
#define MAKE_STRINGS(VAR) #VAR

#define APP_EVENT_TYPE(DO)  DO(DIGIT), DO(DIGIT2)

typedef enum
{
    APP_EVENT_TYPE(MAKE_UNION)
}APP_EVENT_NAME;


const string g_strAryAppEventName[EVENT_NAME_END+1] =
{
    APP_EVENT_TYPE(MAKE_STRINGS)
};


3  delete

#define SAFE_DELETE(p)              {if(NULL != p) {delete p; p = NULL;}}
#define SAFE_DELETE_ARRAY(p)        {if(NULL != p) {delete [] p; p = NULL;}}


4

Before C++11, we could only perform in-class initialization on static const members of integral or enumeration type.Stroustrup discusses this in his C++ FAQ, giving the following example:

class Y {
  const int c3 = 7;           // error: not static
  static int c4 = 7;          // error: not const
  static const float c5 = 7;  // error: not integral
};

5 类型转化

#include <string>
#include <iostream>
#include <sstream>

 int main(void) {
  std::string str;
  std::stringstream stream;
  stream<<"1"<<2;
  stream>>str;

  std::cout<<str<<std::endl;

  return 0;
}

 6      string *ptString1 = false;

    //string *ptString1=true; compile error

    string *ptString1 = false;
    if (!ptString1) {
        cout << "true1" << endl;
    }

    string *ptString2 = NULL;
    if (!ptString2) {
        cout << "true2" << endl;
    }

    string *ptString3 = new string;
    if (ptString3) {
        cout << "true3" << endl;
    }

    int x = 0;
    if (!x) {
        cout << "true4" << endl;
    }

    int y = 1;
    if (y) {
        cout << "true5" << endl;
    }

    java  all compile error


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值