深圳坪山站,查询网站ftp地址,游戏工作室,上海关键词优化排名哪家好隐式类型转换
int i0;
double pi;
强制类型转换
int* pnullptr;
int a(int)p;
单参数构造函数支持隐式类型转换
class A
{
public:A(string a):_a(a){}
private:string _a;
};
A a(xxxx); //xxx const char* 隐式转换为string
多参数也可以通过{…隐式类型转换
int i0;
double pi;
强制类型转换
int* pnullptr;
int a(int)p;
单参数构造函数支持隐式类型转换
class A
{
public:A(string a):_a(a){}
private:string _a;
};
A a(xxxx); //xxx const char* 隐式转换为string
多参数也可以通过{}来实现隐式类型转换。
强制类型转换存在安全问题
const int n 10;
int* p (int*)n;
(*p);
cout n endl; // 10
cout *p endl; // 11
两个值不一样的原因是*p是直接在内存中取值而n没有去内存中取(没有确认改变)直接在寄存器中取。
解决方式volatile 强制从内存中检查出关键字
volatile const int n 10;
C引入四种强制类型转换
static_cast 类型相关
//类型相关
int a 10;
double b static_castint(a);reinterpret_cast 类型不相关
// 类型不相关
int* p a;
int c reinterpret_castint(p);const_cast 删除const属性type 必须是指针或者引用
const int d 10;
inte const_castint(d);
dynamic_cast 父类对象的引用或者指针转换为子类对象
一般情况下C允许向上转换不允许向下转换
class A
{
public :
virtual void f(){}
};
class B : public A
{};
void fun (A* pa)
{
// pa 指向子类对象转换成功转为父类对象返回Null
B* pb2 dynamic_castB*(pa);
coutpb2: pb2 endl;
}
int main ()
{B b;fun(b);return 0;
} 1. dynamic_cast只能用于父类含有虚函数的类 2. dynamic_cast会先检查是否能转换成功能成功则转换不能则返回0 I/O流 I/O流 能更好的打印自定义类型 自动识别类型 运算符重载 cin对象类型转换
int main()
{string str;while (cin str){cout str endl;}return 0;
} cinstr 返回值是cin cin作为while的判断对象。
下面的的类型重载可以让cin隐式转为bool 值 class A
{
public:A(int a0):_a(a){}operator int()//允许转换成int型{ return _a;}operator bool()//允许转换成bool类型{return _a;}int _a;
};
A a10;
int ia;
bool ii a;
operator bool()将cin转换成bool值来作为判断while是否结束。
C文件IO流
class Date
{friend ostream operator (ostream out, const Date d);friend istream operator (istream in, Date d);
public:Date(int year 1, int month 1, int day 1):_year(year), _month(month), _day(day){}operator bool(){// 这里是随意写的假设输入_year为0则结束if (_year 0)return false;elsereturn true;}
private:int _year;int _month;int _day;
};
istream operator (istream in, Date d)
{in d._year d._month d._day;return in;
}
ostream operator (ostream out, const Date d)
{out d._year d._month d._day;return out;
}
二进制写入文件
int main()
{Date d(2013, 10, 14);FILE* fin fopen(file.txt, w);fwrite(d, sizeof(Date), 1, fin);fclose(fin);return 0;
} 文件是字节流二进值的无法正常显示
C二进制写入
Date d(2013, 10, 14);
ofstream ofs(file.txt,ios_base::out|ios_base::binary);
ofs.write((const char*)d, sizeof(d));
按文本的方式写
Date d(2013, 10, 14);
ofstream ofs(file.txt,ios_base::out|ios_base::binary);
ofs d;
调用流插入重载函数。ofs继承out 二进制读写不能用string,vector这样的对象存数据否则写出去就是个指针进程结束就是野指针
流插入时注意空格分隔cin读取时会默认用空格进行分割
读取文件
ifstream ifs(源.cpp);
char ch;
while (ifs.get(ch))
{cout ch;
}