1. nullptr
作用:表示空指針,用於指針初始化。
引入nullptr
原因:
由於之前表示空指針,使用宏NULL
或0
來表示。但是再c和c++中定義如下:
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else /* __cplusplus */
#define NULL ((void *)0)
#endif /* __cplusplus */
#endif /* NULL */
---------------------
作者:Fred^_^
來源:CSDN
原文:https://blog.csdn.net/Xiejingfa/article/details/50478512
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
也就是說在C++
中,NULL
實際上就是0
,在C
中是(void*) 0
。因爲C++是強類型的,無法類型自動轉換。
NULL
缺點:在函數重載中,若參數爲整數和指針時,容易出錯,如下:
void Func(char *);
void Func(int);
int main()
{
Func(NULL); // 調用Func(int)
}
使用方法: 不能賦給整型。
char *pc = nullptr; // OK
int *pi = nullptr; // OK
bool b = nullptr; // OK. b is false.
int i = nullptr; // error
2. 列表初始化
C++11支持列表初始化:
int a = { 20 };
int b{ 10 };
int c[] = { 1,2,3 };
b = { 20 };
與常規初始化不同:
當用於內置類型的變量時,若存在丟失數據的風險,則編譯器回報錯。
int a = { 20 };
double f = 10.1;
a = { f }; //出錯,轉換無效
3. 常量表達式和constexpr
常量表達式:指值不會發生改變並且在編譯階段就可得到結果的表達式。
作用:使用constexpr
表示一個常量表達式
引入原因:以前使用const來表示常量表達式,由兩個方面確定表達式到底是否是常量表達式,數據類型(是否有const)和初始值(初始值是否是常量)。
const int a=20; //是常量表達式
const int b=a+1; //是常量表達式
const int c=size(); //不是常量表達式,因爲size()函數不是常量
由於很難分辨初始值到底是不是常量表達式,所以引用constexpr
。
使用方法:
constexpr int a=20; //是常量表達式
constexpr int b=a+1; //是常量表達式
constexpr int c=size(); //因爲size()函數不是常量,所以報錯
當初始化值不是一個常量時,使用constexpr會報錯,這樣就可以判斷是是常量表達式。
4. using
別名聲明
作用:聲明類型的別名
引入原因:以前使用typedef
來定義類型別名,
typedef int INT;//INT作爲int的別名
INT a=10;//等價於int a=10;
但是typedef
無法很好的用於模板中,因此引入using
。
使用方法:
using INT=int;//INT作爲int的別名
INT a=10;//等價於int a=10;
用於模板中時:
template<typename T1, typename T2> using Map = std::map<T1, std::vector<T2>>;
// Actual type: std::map<std::string, std::vector<std::string>> (as in the original example)
Map<std::string, std::string> map1;
// Actual type: std::map<int, std::vector<int>>
Map<int, int> map2;
5. auto
自動推導類型
作用:auto
讓編譯器通過初始值來推算變量的類型,所以auto
定義的變量必須有初始值。
使用方法:
auto i=0, *p=&i; //i爲整型,p爲整型指針
auto a=10, pi=2.14;// 運行錯誤,a爲整型,pi爲float型。
注意:在一條語句中,聲明多個變量,所有變量的初始基本數據類型必須一樣。
auto一般會忽略頂層const,底層const會保存下來。
const int ci=10,&c=ci; c是ci的別名。
auto a=ci; //a是整數,忽略頂層const
auto b=c; //c是ci的別名,ci本身是頂層const
auto d=&ci; //d是指向整型常量的指針,對常量對象的取地址是一種底層const
可以顯式將頂層const推斷。
const int ci=10,&c=ci; c是ci的別名。
const auto a=ci; //a的類型爲const int 。
6. decltype
類型指示符
作用:返回操作數的數據類型,編譯器分析表達式並得到其返回的數據類型,但不實際計算或調用表達式。
decltype(f()) s=x; //編譯器並不調用f函數,而是將f的返回值類型作爲s的類型。
decltype
處理頂層const
和引用的方式於auto
不同,若使用的表達式是變量,則返回變量的類型(包括頂層const
和引用)。
const int ci=10,&c=ci; c是ci的別名。
decltype(ci) a=0; //a是const int,不忽略頂層const
decltype(c) b=a; //c是ci的引用,b的類型爲const int &
decltype(c) d; //錯誤,因爲引用必須初始化。
- 解引用
int x=10,*p=&x;
int x = 10, *p = &x;
decltype(*p) c = x; //解引用指針可以得到指針的對象,所以結果爲int &,而不是int。
c = 20;
cout << x << endl; //此時x=20,所以c是x的引用。
- 括號 ,加上括號則一定是引用
int x = 10, *p = &x;
decltype(x) c = 20; //c爲int型
decltype((x)) s = x; //s爲x的引用
s = 100;
cout << x << endl << c << endl << s << endl;
則運行結果爲:
100
20
100