C++ Primer 讀書筆記:(P1-P167)

這學(xué)期準(zhǔn)備自學(xué)完這本書税手!1/25/2018 立FLAG為證!

Using File Redirection

$ addItems < infile > outfile

Reference

Reference must be initialized, it cannot be rebinded. A reference is not an object. It is another name(alias) for an existing object.

int ival = 1024;
int &refVal = ival;
refVal = 2; // assigns 2 to ival

Pointer

A pointer is an object. It holds the address of another object. Because references are not objects, they don't have addresses. Hence, we may not define a pointer to reference. Types of the pointer and the object to which it points must match.

Each declarator and relate its variable to the base type differently. For example,

int i = 1024, *p = &i, &r = i;

Here i is an int, p is a pointer, r is a reference. They all relate to the base type int.

Note that int* p is misleading, because in this statement our base type should be int rather than int*. Use int *p instead.

Since reference is not an object, we may not have a pointer to a reference. However, we can have a reference to a pointer. For example,

int i = 42;
int *p;
int *&r = p; // read from right to left. r is a reference to the pointer p
r = &i; // pointer r/p points to i
*r = 0; // change i to 0

For const pointer, always read from right to left. Consider the following example:

int errNumb = 0;
int *const curErr = &errNumb // curErr is a const pointer to int
const double pi = 3.14159
const double *const pip = &pi // pip is a const pointer to a const double type 

void funciton pointer

void pointer can holds the address of any type, but we cannot use a void* to operate on the object it addresses.

// Example program
#include <iostream>
#include <string>

char glFun(int a) { return '2'; } 

int main()
{ 
    char (*pFun)(int); 
    pFun = glFun;
    std::cout << (*pFun)(2);   
}

Here pFun is a function pointer, therefore in the declaration (first line) there is a * before pFun. In main, we first assign the address of function glFun to pFun, and then use the deference operator * to get the value.

We could use typedef to simplify and reuse.

typedef char (*PTRFUN)(int);   
PTRFUN pFun;   
char glFun(int a){ return '2';}   
int main()   
{   
    pFun = glFun;   
    (*pFun)(2);   
}  

constexpr

Runtime constants are those whose initialization values can only be resolved at runtime (when your program is running).

Compile-time constants are those whose initialization values can be resolved at compile-time (when your program is compiling).

In most cases, it doesn’t matter whether a constant value is runtime or compile-time. However, there are a few odd cases where C++ requires a compile-time constant instead of a run-time constant (such as when defining the length of a fixed-size array -- we’ll cover this later). Because a const value could be either runtime or compile-time, the compiler has to keep track of which kind of constant it is.

constexpr double gravity (9.8); // ok, the value of 9.8 can be resolved at compile-time
constexpr int sum = 4 + 5; // ok, the value of 4 + 5 can be resolved at compile-time
 
std::cout << "Enter your age: ";
int age;
std::cin >> age;
constexpr int myAge = age; // not okay, age can not be resolved at compile-time
#include <iostream>
#include <array>
using namespace std;

constexpr int foo(int i)
{
    return i + 5;
}

int main()
{
    int i = 10;
    std::array<int, foo(5)> arr; // OK
    
    foo(i); // Call is Ok
    
    // But...
    std::array<int, foo(i)> arr1; // Error
   
}

作者:藍色
鏈接:https://www.zhihu.com/question/35614219/answer/63798713
來源:知乎
著作權(quán)歸作者所有化戳。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

那用macro纱皆,比如#define MAX_STUDENTS_PER_CLASS 30同眯,可以成為一個我們定義const的解決方案嗎绽昼?

First, because macros are resolved by the preprocessor, which replaces the symbolic name with the defined value, #defined symbolic constants do not show up in the debugger (which shows you your actual code). So although the compiler would compile int max_students = numClassrooms * 30;, in the debugger you’d see int max_students = numClassrooms * MAX_STUDENTS_PER_CLASS;. You’d have to go find the definition of MAX_STUDENTS_PER_CLASS in order to know what the actual value was. This can make your programs harder to debug.

Second, #defined values always have file scope (which we’ll talk more about in the section on local and global variables). This means a value #defined in one piece of code may have a naming conflict with a value #defined with the same file later.

In many applications, a given symbolic constant needs to be used throughout your code (not just in one location). These can include physics or mathematical constants that don’t change (e.g. pi or avogadro’s number), or application-specific “tuning” values (e.g. friction or gravity coefficients). Instead of redefining these every time they are needed, it’s better to declare them once in a central location and use them wherever needed. That way, if you ever need to change them, you only need to change them in one place.

There are multiple ways to facilitate this within C++, but the following is probably easiest:

  1. Create a header file to hold these constants
  2. Inside this header file, declare a namespace
  3. Add all your constants inside the namespace (make sure they’re const)
  4. include the header file wherever you need it

e.g. constants.h:

#ifndef CONSTANTS_H
#define CONSTANTS_H
 
// define your own namespace to hold constants
namespace constants
{
    constexpr double pi(3.14159);
    constexpr double avogadro(6.0221413e23);
    constexpr double my_gravity(9.2); // m/s^2 -- gravity is light on this planet
    // ... other related constants
}
#endif
#include "constants.h"
double circumference = 2 * radius * constants::pi;

extern

const is local to the file. If we want to share across files, use extern const int v_name.

decltype - declare type

decltype(f()) sum = x;
相關(guān)資料

HEADER GUARDS

#ifndef MATH_H
#define MATH_H
 
int getSquareSides()
{
    return 4;
}
 
#endif

HEADER GUARDS prevent the same header file being copied to the code multiple times.

using

using declaration let us use a name from a namespace without qualifying the name. In general, code inside headers should not contain using, because header file codes may be coped into a program which doesn't want using that namespace.

string

string s4(10, 'c'); // cccccccccc
getline(cin,line) would discard the newline.

vector

vector is a template, not a type. Types generated from vector must include the element type, for example, vector<int>.

array

char a[6] = "Daniel"; // this doesn't compile as there is no space for null
char a1[] = "Daniel"; // this works
char a2[] = {'C','\0'} // this works too

int a[] = {0,1,2};
int a1[] = a; // not legal! no initialize/assign between arrays

Define a pointer or reference to an array, we could read inside out - first read the right to get size, then left to get type.

int (*Parray)[10] = &arr; // Parray is a pointer to an array of ten ints
int (&arrRef)[10] = arr; // arrRef is an alias for an arr
int *(&arry)[10] = ptrs; // arry is a reference to ten int pointers

When we use a variable to subscript an array, we normally should define that variable to have type size_t.

The [] subscript operator in array is the one that is defined as part of the language. The [] subscript operator in vector is defined by library vector template and applies to operands of type vector.

Character Arrays Are Special

Character arrays have an additional form of initialization: We can initialize such arrays from a string literal. When we use this form of initialization, it is important to remember that string literals end with a null character. That null character is copied into the array along with the characters in the literal:

char a1[] = {'C', '+', '+'}; // list initialization, no null 
char a2[] = {'C', '+', '+', '\0'}; // list initialization, explicit null 
char a3[] = "C++"; // null terminator added automatically 
const char a4[6] = "Daniel"; // error: no space for the null!

We cannot initialize an array as a copy of another array, nor is it legal to assign one array to another:

int a[] = {0, 1, 2}; // array of three ints 
int a2[] = a; // error: cannot initialize one array with another 
a2 = a; // error: cannot assign one array to another

Reference:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市须蜗,隨后出現(xiàn)的幾起案子硅确,更是在濱河造成了極大的恐慌目溉,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,496評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件菱农,死亡現(xiàn)場離奇詭異缭付,居然都是意外死亡,警方通過查閱死者的電腦和手機循未,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,187評論 3 385
  • 文/潘曉璐 我一進店門陷猫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人的妖,你說我怎么就攤上這事绣檬。” “怎么了嫂粟?”我有些...
    開封第一講書人閱讀 157,091評論 0 348
  • 文/不壞的土叔 我叫張陵娇未,是天一觀的道長。 經(jīng)常有香客問我星虹,道長零抬,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,458評論 1 283
  • 正文 為了忘掉前任宽涌,我火速辦了婚禮平夜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘护糖。我一直安慰自己褥芒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,542評論 6 385
  • 文/花漫 我一把揭開白布嫡良。 她就那樣靜靜地躺著锰扶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪寝受。 梳的紋絲不亂的頭發(fā)上坷牛,一...
    開封第一講書人閱讀 49,802評論 1 290
  • 那天,我揣著相機與錄音很澄,去河邊找鬼京闰。 笑死,一個胖子當(dāng)著我的面吹牛甩苛,可吹牛的內(nèi)容都是我干的蹂楣。 我是一名探鬼主播,決...
    沈念sama閱讀 38,945評論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼讯蒲,長吁一口氣:“原來是場噩夢啊……” “哼痊土!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起墨林,我...
    開封第一講書人閱讀 37,709評論 0 266
  • 序言:老撾萬榮一對情侶失蹤赁酝,失蹤者是張志新(化名)和其女友劉穎犯祠,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酌呆,經(jīng)...
    沈念sama閱讀 44,158評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡衡载,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,502評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了隙袁。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片痰娱。...
    茶點故事閱讀 38,637評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖菩收,靈堂內(nèi)的尸體忽然破棺而出猜揪,到底是詐尸還是另有隱情,我是刑警寧澤坛梁,帶...
    沈念sama閱讀 34,300評論 4 329
  • 正文 年R本政府宣布,位于F島的核電站腊凶,受9級特大地震影響划咐,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜钧萍,卻給世界環(huán)境...
    茶點故事閱讀 39,911評論 3 313
  • 文/蒙蒙 一褐缠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧风瘦,春花似錦队魏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,744評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至瞬雹,卻和暖如春昧谊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背酗捌。 一陣腳步聲響...
    開封第一講書人閱讀 31,982評論 1 266
  • 我被黑心中介騙來泰國打工呢诬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胖缤。 一個月前我還...
    沈念sama閱讀 46,344評論 2 360
  • 正文 我出身青樓尚镰,卻偏偏與公主長得像,于是被迫代替她去往敵國和親哪廓。 傳聞我的和親對象是個殘疾皇子狗唉,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,500評論 2 348

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,435評論 0 23
  • 我的愛人吶 你現(xiàn)在是否正輕佻著撫弄她的秀發(fā) 欣賞她婀娜多姿的魔鬼身材 內(nèi)心的小野獸狂跳不已 我的愛人吶 你現(xiàn)在是否...
    滑納溪閱讀 271評論 2 4
  • 開發(fā)過程中總會有XCode的升級,但也避免不了會使用到之前的版本撩独,AppStore上只能獲取到最新的版本敞曹,網(wǎng)上也有...
    SunshineAutumn閱讀 735評論 0 0
  • 為了培養(yǎng)學(xué)生學(xué)習(xí)英語的興趣账月,提高學(xué)生的學(xué)習(xí)積極性,南村校區(qū)舉行了英語文化節(jié)活動澳迫,這是英語文化節(jié)活動(3)局齿。英語單詞...
    金子發(fā)光閱讀 210評論 0 0