C/C++语言基础
1. 一个子类中含有其他类对象,则构造函数的顺序是?
先执行基类的(如果基类当中有虚基类,要先执行虚基类的,其他基类则按照声明派生类是的顺序依次执行),在执行成员对象的,最后执行自己的。
2.sprintf的使用,还有itoa(),ltoa(),ultoa(),gcvt(),ecvt();使用sprintf系列函数把数字转换成字符串,其比itoa()系列函数运行速度慢;与sprintf对应的是sscanf函数, 可以将字符 串转换成数字。字符串转化为数字:atof(),atoi(),atol()等。
#include <iostream> #include <cstdio> using namespace std; const int maxn=0; int main() { char str[100]; sprintf(str,"%d",1234); cout<<"十进制1:"<<str<<endl;//1234 sprintf(str,"% 10d",1234); cout<<"十进制2:"<<str<<endl;// 1234 sprintf(str,"%o",1234); cout<<"八进制1:"<<str<<endl;//2322 sprintf(str,"%#o",1234); cout<<"八进制2:"<<str<<endl;//02322 sprintf(str,"%x",1234); cout<<"十六进制1:"<<str<<endl;//4d2 sprintf(str,"%#x",1234); cout<<"十六进制2:"<<str<<endl;//0x4d2 sprintf(str,"%#X",1234); cout<<"十六进制3:"<<str<<endl;//0x4D2 sprintf(str,"%08X",1234); cout<<"十六进制4:"<<str<<endl;//000004D2 sprintf(str,"%f",3.1415926); cout<<str<<endl;//3.141593 sprintf(str,"%f",30.1415926); cout<<str<<endl;//30.141593 //打印宽度为10,小数点后保留三位 //宽度不足,默认补0 sprintf(str,"%10.3f",3.1415926); cout<<str<<endl;// 3.142 sprintf(str,"%010.3f",3.1415926); cout<<str<<endl;//000003.142 sprintf(str,"%.3f",3.1415926); cout<<str<<endl;//3.142 /** int i=100; sprintf(str,"%.2f",i); cout<<str<<endl; //注意,注释int i=100前无关代码 //运行结果为0.00!!! sprintf(str,"%.2f",(double)i); cout<<str<<endl;//100.00 */ char str[] = "15.455"; int i; float fp; sscanf( str, "%d", &i ); // 将字符串转换成整数 i = 15 sscanf( str, "%f", &fp ); // 将字符串转换成浮点数 fp = 15.455000 return 0; }
3.