---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Types and Declaration
(1)Boolean Type
(2)Knowing Ranges of Types
#include <limits>
// Implementation-dependent
#include <limits>
int main()
{
cout << "largest integer = "
<< numeric_limits<int>::max();
cout << “smallest integer = "
<< numeric_limits<int>::min();
return 0;
}
int类型
#include <limits>
int main()
{
cout << "largest float = "
<< numeric_limits<float>::max();
cout << “float nearest to zero = "
<< numeric_limits<float>::min();
return 0;
}
float类型
(3)Binary Literal
(4)Declaration
A. Declaration vs. definition:
A Definition is a declaration that defines an entity for the identifier.
A declaration may not be a definition.
Definition exactly once, declaration many times.
B. Declaration Examples:
string s;
double sqrt(double);
template <class T> T abs(T a) // Template模板定义各类abs()函数
{ return a<0?-a:a;}
typedef complex<short> Point; // typedef定义了新的类型名,并未定义新的类型,只能定义一次
struct User;
namespace NS{ int a; }
constexpr double pi=3.14;
using PointT = complex<short>;
wchar_t chineseCharacter = L’汉’ // 开头L表示用Unicode编码汉字,类型是wchar_t
basic_string<wchar_t>
chStr = L”汉字”;
extern int a;
const c=7;
// Error! Lack of type
gt(int a, int b)
{ return a>b?a:b;}
// Error! Lack of return type
// "implicit int" Rule
// not allowed in C++!
C. Using Global Identifier :
::globalId can be used in a local scope, even its name is identical to local one.
int x;
void f()
{
int x=1;
::x=2; // 修改的是全局变量x的值
x=3; // 修改f()中的变量x的值
…
}
auto i{0};
vector<string> v; …
for (const auto& x : v) cout << x << '\n';
for (auto i : {1, 2, 3, 4, 5, 6, 7})
cout << i << '\n';
four syntactic styles:
T a1 {v};
T a2 = {v};
T a3 = v;
T a4(v);
prefer = when using auto.
auto a2 = {v};
auto a3 = v;
(1)Variable-size arrays
#include <vector>
using namespace std;
void f(int i)
{
vector<int> v1(i);
vector<int> v2{1,2,3};
vector<int> v3(i,10);
…
}
·Constants and Literals
·Keyword const as a modifier
·A constant identifier must be initialized and cannot be assigned
·Prefer to #define macro usage
·Using symbolic constants is better than using literals in the large programs
·const int model=90;
·const int v[]={1,2,3,4};
·const double PI=3.14;
·constexpr double PI1=3.14;
·const double PI2{3.14};
(3)Pointers and Constant P56-57
A. 指向常量的指针
const int someInt=10;
const int *p = &someInt;
Or
int const *p = &someInt;
// *p is a constant, p is a variable
B. const指针
int someInt=10;
int *const p = &someInt;
// p is a constant
C.指向常量+const指针
const int someInt=10;
const int *const p = &someInt;
Or
int const *const p = &someInt;
// *p is a constant, p is a constant too.
void f(char*p)
{ char s[]="Gorm";
const char* pc=s;
pc[3]='g'; //Error!
pc=p;
char* const cp=s;
cp[3]='g';
cp=p; //Error!
const char* const cpc=s;
cpc[3]='g'; //Error!
cpc=p; //Error!
}
void f4( )
{ int a