C++进阶学习(二)字面量、noexcept
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
三、字面量
用户定义字面量是对字面量运算符""的重载双引号后必须以_开头进行命名重载时函数传入相应的参数类型如字符串需传入字符串首地址及长度
void operator""_t(const char *str, size_t size)
{
cout << str << endl;
}
int main()
{
cout << "---begin---" << endl;
"hello world"_t;
cout << "---end---" << endl;
return 0;
}
输出结果
---begin---
hello world
---end---
标准库中的字面量后可能不加_
int main()
{
cout << "---begin---" << endl;
using namespace literals;
cout << "hello world"s << endl;
cout << "---end---" << endl;
return 0;
}
输出结果
---begin---
hello world
---end---
*同样我们还可以对数字类型进行定义
size_t operator""_i(size_t n)
{
return n + 1;
}
int main()
{
cout << "---begin---" << endl;
cout << 5_i << endl;
cout << "---end---" << endl;
return 0;
}
输出结果
---begin---
6
---end---
但是字面量运算符仅允许包括const char*, size_t, long double, unsigned long long int, char等在内的形参列表而不包含常用的int, double等类型。
四、noexcept关键字
异常说明符noexcept既可以用作说明符也可以用作运算符
当函数进行noexcept运算时默认返回false当函数被noexcept修饰时返回值为true
作为说明符时也可以通过noexcept(表达式)的方式进行指定
void func1()
{
cout << "func1" << endl;
}
void func2() noexcept
{
cout << "func2" << endl;
}
int main()
{
cout << "---begin---" << endl;
cout << noexcept(func1()) << endl;
cout << noexcept(func2()) << endl;
cout << "---end---" << endl;
return 0;
}
输出结果
---begin---
0
1
---end---
不能仅通过异常说明的不同实现函数重载
void func()
{
cout << "func" << endl;
}
void func() noexcept
{
cout << "func" << endl;
}
// error: redefinition of 'void func()'
C++17起noexcept会作为函数的一部分指向不会抛出异常的函数指针可以隐式转换到可能会抛出异常的函数指针反之则不行
void func1()
{
cout << "func1" << endl;
}
void func2() noexcept
{
cout << "func2" << endl;
}
int main()
{
cout << "---begin---" << endl;
// void (*ptr1)() noexcept = func1; /*error*/
void (*ptr)() = func2;
cout << "---end---" << endl;
return 0;
}
作为运算符时noexcept与typeid,sizeof,decltype,requires类似其操作数都是不求值表达式这些运算符都只会查询操作数的编译期性质
int main()
{
cout << "---begin---" << endl;
int i = 0;
cout << noexcept(i++) << endl;
cout << i << endl;
cout << "---end---" << endl;
return 0;
}
输出结果
---begin---
1
0
---end---