C++提供了许多关键字供开发人员使用,其中有以下几点需要注意的地方:
- inline:对代码展开,拿空间换时间
- namespace解决同名冲突
- noexcept:不抛出异常声明函数
- extern:主要用于不同文件常量共享
- not等价于=!
- not_eq等价于!=
- signed:带符号的int
- or 等价于 ||
- or_eq 等价于 |=
- static_assert:检测编译期条件
- assert:运行时候检测代码
- class和struct主要区别在于默认继承和访问权限class是private,struct是public其余基本一样
- using和typedef类似
- nullptr C++11引入空指针主要用于定义模板类时和0的区别
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 c / 0
nullPointer(nullptr);
func(nullPointer, nullptr);
func(nullPointer, (int*)0);
func(nullPointer, NULL);
}
- operator:重载操作符
struct AAA{
int operator & () {
return 10;
}
};
void testOperator(){
AAA a;
auto address = &a;
}
struct AAA {
~AAA() { delete m_value;}
AAA() : m_value(new int()) {}
AAA(const AAA& rhs) : m_value(new int(*(rhs.m_value))) {}
AAA& operator = (const AAA& rhs) {
*m_value = *(rhs.m_value);
return *this;
}
// = == < >= > <= !=
// +
// +=
private:
int* m_value;
};
void testOperator(){
AAA a;
AAA b = a;
b = a;
}
- reinterpret_cast转换
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的使用:
171、静态声明可以放文件里表示文件范围内全局可见且编译的时候就已经分配内存空间
17.2、放函数里表示函数的一个状态只在第一运行时执行一次
17.3、放结构体里只是从属是所有结构体共用的不占结构体size
//static放结构体里的情况
struct S {
static int s;
};
// sizeof(S) == 1
int S::s = 10;
struct Foo;
struct SS {
static int a[];
static Foo foo;
static SS ss;
};
int SS::a[10];
struct Foo {};
Foo SS::foo;
SS SS::ss;