C++关键字(2)

explicit

指定构造函数或转换函数为显示,即它不能用于隐式转换和复制初始化。

explicit说明符只能出现在类定义之内的构造函数或转换函数的声明说明符序列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct A{
A(int){}
A(int,int){}
operator int() const { return 0;}
};

struct B{
explicit B(int){}
explicit B(int,int){}
explicit operator int() const { return 0;}
};

void TestExpl(){
A a1 = 1; // A a1 = A(1);
// B b1 = 1; //error
A a2(2);
B b2(2); //OK
A a3 = {4,5}; // A a3 = A{4,5}; A{4,5};
// B b3 = {4,5};//error
int na1 = a1; //OK
//int na1 = b2; //error
int na2 = static_cast<int>(a1);
int nb2 = static_cast<int>(b2);
A a4 = (A)1;
B b4 = (B)1;
}
nullptr

C++11引入的,指代空指针。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename T, typename U>
void func(T t, U u){
t(u);
}

void nullPointer(int* a){
std::cout << "i'm a pointer\n'";
}

void testNullPointer(){
nullPointer(0);
nullPointer(NULL); //(void*)0
nullPointer(nullptr);// std::nullptr_t
func(nullPointer, nullptr); //OK
//模板推导会去找 函数nullPointer(int),而不是nullPointer(int*)
func(nullPointer, 0); //error
func(nullPointer, NULL); //error
}
operator

当重载一些特殊操作符时,一定要小心,可能会一些预想之外的问题。

1
2
3
4
5
6
7
8
9
10
11
struct AAA{
int operator &(){
return 10;
}
};

void testOperator(){
AAA a;
//这里&已经不是获取地址的功能了
auto address = &a;
}
reinterpret_cast

类型转换(类似于int转char*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct AAA{};

void testReinter(){
int a = 1;
auto p = reinterpret_cast<char*>(&a);
if(p[0] == 1) std::cout << "the system is little endian\n";
else std::cout << "the system is big endian\n";
// reinterpret_cast
// static_cast
// const_cast
// dynamic_cast

// c like cast
auto pp = (char*)(&a);
const AAA bb;
auto pbb = const_cast<AAA*>(&bb);
auto cbb = (AAA*)(&bb);
int c = 100;
auto cc = static_cast<char>(c);
auto ccc = (char)c;
}
static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//全局变量在其他文本extern声明后可访问,static不允许
static int globalA = 0;
void printStatic(){
static int localStatic = 0;
++localStatic;
std::cout << localStatic << std::endl;
}

struct S{
static int s;
};
//sizeof(S) = 1 // S == empty

int S:s = 10;

void testStaticAssert(){
static_assert((sizeof(int) == 4) && "only work for int for 32 bit");
int a = 4;
int b = 5;
assert(a == b);
}
static_assert&assert
1
2
3
4
5
6
7
void testStaticAssert(){
//static_assert在编译期检查,assert在运行期检查 debug模式下生效
static_assert((sizeof(int) == 4) && "only work for int for 32 bit");
int a = 4;
int b = 5;
assert(a == b);
}
typedef
1
2
3
4
5
6
7
8
9
10
typedef unsigned long ulong;
class testTypedef(){
typedef std::map<int, ulong> Group;
Group a;
void aa(){
// std::map<int, ulong>::itertor iter = a.find(10);
// Group::iteator iter = a.find(10);
auto iter = a.find(10);
}
};

本文标题:C++关键字(2)

文章作者:Tokey

发布时间:2020年03月13日 - 15:03

最后更新:2021年06月29日 - 22:06

原始链接:http://TokeyRoad.github.io/2020/03/13/C++关键字-2/

许可协议: 转载请保留原文链接及作者。

0%