C++技巧

文件

打开文件时判断文件是否存在:

ifstream f("123.txt");
if (!f)
    cout<<"不存在";

获取文件大小:

f.seekg (0, ios::end);
length = f.tellg();

 根据年月日获取日期

#include<iostream>
#include<ctime>
using namespace std;

int date2week(int date)
{
    time_t rawTime;
    time(&rawTime);
    struct tm* timeInfo = localtime(&rawTime);
    timeInfo->tm_year = date / 10000 - 1900;
    timeInfo->tm_mon = date/100 %100 - 1;
    timeInfo->tm_mday = date % 100;
    mktime(timeInfo);
    return timeInfo->tm_wday;
}

void main()
{
    cout<<date2week(19840713)<<endl;
}

 四种类型转换

class A {};
class B : public A {};
class C : public A {};
class D {};

reinterpret_cast就像传统的类型转换一样对待所有指针的类型转换,也可以进行指针和整数之间的转换。

A* a = new A;
D* d = reinterpret_cast<D*>(a);
int* e = reinterpret_cast<int*>(a);

static_cast允许执行任意的隐式转换和相反转换动作也能用基础类型之间的标准转换

A* a = new A;
B* b = static_cast<B*>(a);
double d = 3.14159265;
int    i = static_cast<int>(d);

dynamic_cast只用于对象的指针和引用。 

可以执行类的上下行转换和类间交叉转换(B和C之间的转换)。上行转换的时候跟static_cast一样,下行转换时具有类型检查功能,比static_cast好。 

基类必须有虚函数,static_cast没有这个限制。 

B* b = new B;
A* a = dynamic_cast<A*>(b);

如果类型A不是b的某个基类型,该操作将返回一个空指针

const_cast设置或者是移除对象的const属性

const A* b = new A;
A* c = const_cast<A*>(b);

 宏:

#ifdef __AFX_H__ //判断是否使用MFC

#if defined (_MSC_VER) //是否使用VC编译器

#elif defined (__GNUC__) //使用gcc编译器

#ifdef __cplusplus #判断是c++还是c

判断操作系统

#ifdef WIN32

#ifdef linux

#ifdef __sun

posted on 2013-06-28 21:25  赛欧拉  阅读(223)  评论(0编辑  收藏  举报