Back to VNotes

C++ / Syntax

现代 C++ 语法笔记(二)

整理原始字面量、long long、成员初始化、模板、异常等现代 C++ 语法点。

数值类型与字符串的转换

数值类型转字符串

使用<string>中的 to_string 函数

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

字符串转数值类型

使用<sting>中的各种stox函数

int       stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
long      stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long      stoul( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );
float       stof( const std::string& str, std::size_t* pos = 0 );
double      stod( const std::string& str, std::size_t* pos = 0 );
long double stold( const std::string& str, std::size_t* pos = 0 );
  • str:要转换的字符串
  • pos:传出参数, 记录从哪个字符开始无法继续进行解析, 比如: 123abc, 传出的位置为3
  • base:若 base 为 0 ,则自动检测数值进制:若前缀为 0 ,则为八进制,若前缀为 0x 或 0X,则为十六进制,否则为十进制。

注意:

  • 当字符串只有前半部分是数字时(如123abc),只有前面的数字部分会被处理并返回
  • 当字符串的开头不是数字时会转换失败,引发错误

静态断言

断言

使用断言,包含<cassert><assert.h>头文件中的宏assert

将一个结果必须为真的表达式放在语句中作为断言,用于排除不该出现的情况

char* createArray(int size)
{
    // 通过断言判断数组大小是否大于0
    assert(size > 0);	// 必须大于0, 否则程序中断
    char* array = new char[size];
    return array;
}

静态断言

上面所说的断言是运行时断言,C++11提供了静态断言,无需包含头文件,在编译时就会进行检查

并且可以自定义违反断言时的错误信息

static_assert(参数1, 参数2);
  • 参数1:断言表达式,这个表达式通常需要返回一个 bool值,且不能包含变量,只能有常量,因为是在编译时检查
  • 参数2:警告信息,它通常就是一段字符串,在违反断言(表达式为false)时提示该信息

 static_assert(sizeof(long) == 4, "错误, 不是32位平台...");

只有静态断言才能检查出错误,因为sizeof在编译时计算,这是运行时断言无法确定的

异常

throw抛出异常

在C++中,通过throw关键字来抛出异常

int devide(int a, int b)
{
	if(b == 0)
	{
		throw "devide by zero";
	}
	int result = a/b;
	return result;
}

throw后面通常跟着一个表达式,类型可以是任何类型,通常是内置类型或自定义异常类