目录
nullptr
在C++11中,NULL使用nullptr来代替
#include <iostream>
using namespace std;
void func(int)
{
cout << "1" << endl;
}
void func(char*)
{
cout << "2" << endl;
}
int main()
{
// NULL就是0
func(NULL); // 1
func(nullptr); // 2
return 0;
}
类型推导auto、decltype
C++11中引入,使用auto关键字可以进行类型推导
!!auto不能在参数类型和数组中使用
#include <iostream>
using namespace std;
class Test
{
public:
void func()
{
cout << "hello" << endl;
}
};
int main()
{
auto i = 1;
auto d = 3.14;
auto a = i+d;
cout << a << endl; // 4.14
// t的类型被推导为Test*
auto t = new Test;
cout << t << endl;
t->func();
return 0;
}
auto只能对变量进行类型推导,decltype可以对表达式进行类型推导
#include <iostream>
using namespace std;
class Test
{
public:
void func()
{
cout << "hello" << endl;
}
};
int main()
{
int i = 1;
double d = 3.14;
// 计算i*d这个表达式的数据类型
// 因为z是浮点型,所以此处的z为double类型
decltype(i*d) z = 2.22;
cout << z << endl;
return 0;
}
格式化输出
#include <iostream>
#include <iomanip> // 输出域
using namespace std;
int main()
{
int i = 10;
// 开启进制显示功能(十进制无效)
cout << showbase;
// 切换为8进制输出
cout << oct;
cout << i << endl; // 012
// 切换为16进制输出
cout << hex;
cout << i << endl; // 0xa
// 切换回十进制
cout << dec;
cout << i << endl; // 10
// 取消进制显示
cout << noshowbase;
// 设置输出域的宽度
// 如果设置输出域宽度小于数据宽度,还会显示数据宽度
cout << setw(7) << "1=1x1" << endl;
cout << setw(1) << "2=1x2" << setw(7) << "4=2x2" << endl;
cout << setw(7) << "15=3x5" << setw(7) << "81=9x9" << endl;
return 0;
}
字符串与数字转换
借助字符串流来完成字符串与数字之间的转换,需要引入头文件:
//我这么写总不会再因为尖括号隐藏吧
#include <sstream>
#include <iostream>
#include <sstream> // 字符串流
using namespace std;
int main()
{
// int → string
int i = 123;
stringstream ss;
ss << i;
string s = ss.str();
cout << s.append("abc") << endl;
// string → int
s = "666";
stringstream ss2(s);
ss2 >> i;
cout << ++i << endl;
return 0;
}