周记 2020.03.09-03.15

C++语法

explicit

explicit用来修饰构造函数、转换函数(C++11)、推导指引(C++17),C++20可以在其后加表达式(详见:https://zh.cppreference.com/w/cpp/language/explicit)。

功能

  • 被修饰的构造函数的类,不能进行隐式类型转换,只能进行显示类型转换
  • 不能用于复制初始化

注意

  • explicit只能用于构造函数的声明

这篇博文中的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* without explicit */

class circle
{
public:
circle(double r) : R(r) {}
circle(int x, int y = 0) : X(x), Y(y) {}
circle(const circle& c) : R(c.R), X(c.X), Y(c.Y) {}
private:
double R;
int X, Y;
};

int _tmain()
{
circle A = 1.23;
circle B = 123;
circle C = A;

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* with explicit */
class circle
{
public:
explicit circle(double r) : R(r) {}
explicit circle(int x, int y = 0) : X(x), Y(y) {}
explicit circle(const circle& c) : R(c.R), X(c.X), Y(c.Y) {}
private:
double R;
int X, Y;
};

int _tmain()
{
circle A(1.23);
circle B(123);
circle C(A);
}

在结构中也可以这么用。

非常量引用的初始值必须是左值

可能是存在不被允许的隐式类型转换。

assert

assert是宏,不仅用来报错。