forked from t-towtdi/B.Eckel-Thinking-in-CPP-vol.1
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Chapter 8 samples source code were added
- Loading branch information
Tim Towtdi
committed
Jan 17, 2013
1 parent
2238ebe
commit 7b17041
Showing
19 changed files
with
418 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
//: C08:BuiltInTypeConstructors.cpp | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class B { | ||
int i; | ||
public: | ||
B(int ii); | ||
void print(); | ||
}; | ||
|
||
B::B(int ii) : i(ii) {} | ||
void B::print() {cout << i << endl; } | ||
|
||
int main() { | ||
B a(10), b(2); | ||
float pi(3.14159); | ||
a.print(), b.print(); | ||
cout << pi << endl; | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
//: C08:Castaway.cpp | ||
// Отмена константности преобразованием типа | ||
|
||
class Y { | ||
int i; | ||
public: | ||
Y(); | ||
void f() const; | ||
}; | ||
|
||
Y::Y() { i = 0; } | ||
|
||
void Y::f() const { | ||
//! i++; // Ошибка -- константная функция класса | ||
((Y*)this)->i++; // Можно: отмена константности | ||
// Рекомендуемый синтаксис явного приведения типов C++; | ||
(const_cast<Y*>(this))->i++; | ||
} | ||
|
||
int main() { | ||
const Y yy; | ||
yy.f(); // Фунция изменяет константный объект! | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
//: C08:ConstInitialization.cpp | ||
// Èíèöèàëèçàöèÿ êîíñòàíò â êëàññàõ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class Fred { | ||
const int size; | ||
public: | ||
Fred(int sz); | ||
void print(); | ||
}; | ||
|
||
Fred::Fred(int sz) : size(sz) {} | ||
void Fred::print() { cout << size << endl; } | ||
|
||
int main() { | ||
Fred a(1), b(2), c(3); | ||
a.print(), b.print(), c.print(); | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
//: C08:ConstMember:cpp | ||
class X { | ||
int i; | ||
public: | ||
X(int ii); | ||
int f() const; | ||
}; | ||
|
||
X::X(int ii) : i(ii) {} | ||
int X::f() const { return i; } | ||
|
||
int main() { | ||
X x1(10); | ||
const X x2(20); | ||
x1.f(); | ||
x2.f(); | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
//: C08:ConstPointer.cpp | ||
// Ïåðåäà÷à óêàçàòåëåé íà êîíñòàíòû | ||
// â àðãóìåíòàõ è âîçâðàùàåìûõ çíà÷åíèÿõ | ||
|
||
void t(int*) {} | ||
|
||
void u(const int* cip) { | ||
//! *cip = 2; // Íåëüçÿ -- ìîäèôèêàöèÿ çíà÷åíèÿ | ||
int i = *cip; // Ìîæíî -- êîïèðîâàíèå çíà÷åíèÿ | ||
//! int* ip2 = cip // Íåëüçÿ -- íå êîíñòàíòà | ||
} | ||
|
||
const char* v() { | ||
// Âîçâðàùåíèå àäðåñà ñòàòè÷åñêîãî ñèìâîëüíîãî ìàññèâà: | ||
return "result of function v()"; | ||
} | ||
|
||
const int* const w() { | ||
static int i; | ||
return &i; | ||
} | ||
|
||
int main() { | ||
int x = 0; | ||
int* ip = &x; | ||
const int* cip = &x; | ||
t(ip); // Ìîæíî | ||
//! t(cip); // Íåëüçÿ | ||
u(ip); // Ìîæíî | ||
u(cip); // Òîæå ìîæíî | ||
//! char* cp = v(); // Íåëüçÿ | ||
const char* ccp = v(); // Ìîæíî | ||
//! int* ip2 = w(); // Íåëüçÿ | ||
const int* const ccip = w(); // Ìîæíî | ||
const int* cip2 = w(); // Ìîæíî | ||
//! *w() = 1; // Íåëüçÿ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
//: C08:ConstPointers.cpp | ||
const int* u; | ||
int const* v; | ||
int d = 1; | ||
int* const w = &d; | ||
const int* const x = &d; // (1) | ||
int const* const x2 = &d; // (2) | ||
int main() {} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
//: C08:ConstReturnValues.cpp | ||
// Возвращение константы по значению | ||
// Результат не может использоваться в качестве l-значения | ||
|
||
class X { | ||
int i; | ||
public: | ||
X(int ii = 0); | ||
void modify(); | ||
}; | ||
|
||
X::X(int ii) { i = ii; } | ||
|
||
void X::modify() { i++; } | ||
|
||
X f5() { | ||
return X(); | ||
} | ||
|
||
const X f6() { | ||
return X(); | ||
} | ||
|
||
void f7(X& x) { // Передача по неконстантной ссылке | ||
x.modify(); | ||
} | ||
|
||
int main() { | ||
f5() = X(1); // Можно -- неконстантное возвращаемое значение | ||
f5().modify(); // Можно | ||
//! f7(f5()); // Предупреждение или ошибка | ||
// Ошибки компиляции | ||
//! f6() = X(1); | ||
//! f6().modify(); | ||
//! f7(f6()); | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
//: C08:ConstTemporary.cpp | ||
// Временные объекты являются константными | ||
|
||
class X {}; | ||
|
||
X f() { return X(); } // Возвращение по значению | ||
|
||
void g1(X&) {} // Передача по обычной ссылке | ||
void g2(const X&) {} // Передача по ссылке на константу | ||
|
||
int main() { | ||
// Ошибка: f() создает константный временный объект: | ||
//! g1(f()); | ||
// Можно: g2 получает ссылку на константу | ||
g2(f()); | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
//: C08:Constag.cpp | ||
// Êîíñòàíòû è àãðåãàòû | ||
const int i[] = {1, 2, 3, 4}; | ||
//! float f[i[3]]; // Íåäîïóñòèìî | ||
struct S {int i, j; }; | ||
const S s[] = {{1, 2}, {3, 4}}; | ||
//! double d[s[1].j];// Íåäîïóñòèìî | ||
int main() {} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
//: C08:Constval.cpp | ||
// Возвращение констант по значению | ||
// бесмысленно для встроенных типов | ||
|
||
int f3() { return 1; } | ||
const int f4() { return 1; } | ||
|
||
int main() { | ||
const int j = f3(); // Работает нормально | ||
int k = f4(); // Но и это тоже работает | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
//: C08:EncapsulatingTypes.cpp | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class Integer { | ||
int i; | ||
public: | ||
Integer(int ii = 0); | ||
void print(); | ||
}; | ||
|
||
Integer::Integer(int ii) : i(ii) {} | ||
void Integer::print() { cout << i << ' '; } | ||
|
||
int main() { | ||
Integer i[100]; | ||
for (int j = 0; j < 100; j++) | ||
i[j].print(); | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
//: C08:EnumHack.cpp | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class Bunch { | ||
enum { size = 1000 }; | ||
int i[size]; | ||
}; | ||
|
||
int main() { | ||
cout << "sizeof(Bunch) = " << sizeof(Bunch) | ||
<< ", sizeof(i[1000[) = " | ||
<< sizeof(int[1000]) << endl; | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
//: C08:Mutable.cpp | ||
// Êëþ÷åâîå ñëîâî "mutable" | ||
|
||
class Z { | ||
int i; | ||
mutable int j; | ||
public: | ||
Z(); | ||
void f() const; | ||
}; | ||
|
||
Z::Z() : i(0), j(0) {} | ||
|
||
void Z::f() const { | ||
//! i++; // Îøèáêà -- êîíñòàíòíàÿ ôóíêöèÿ | ||
j++; // Ìîæíî: mutable | ||
} | ||
|
||
int main() { | ||
const Z zz; | ||
zz.f(); // Ôóíêöèÿ èçìåíÿåò êîíñòàíòíûé îáúåêò! | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
//: C08:PointerAssignment.cpp | ||
int d = 1; | ||
const int e = 2; | ||
int* u = &d; // Ìîæíî -- d íå ÿâëÿåòñÿ êîíñòàíòîé | ||
//! int* v = &e; // Íåëüçÿ -- å ÿâëÿåòñÿ êîíñòàíòîé | ||
int* w = (int*)&e; // Ìîæíî, íî ýòî ïëîõîé ñòèëü | ||
int main() {} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
//: C08:Quoter.cpp | ||
// Ñëó÷àéíûé âûáîð öèòàòû | ||
#include <iostream> | ||
#include <cstdlib> // Ãåíåðàòîð ñëó÷àéíûõ ÷èñåë | ||
#include <ctime> // Ðàñêðóòêà ãåíåðàòîðà ñëó÷àéíûõ ÷èñåë | ||
using namespace std; | ||
|
||
class Quoter { | ||
int lastquote; | ||
public: | ||
Quoter(); | ||
int lastQuote() const; | ||
const char* quote(); | ||
}; | ||
|
||
Quoter::Quoter() { | ||
lastquote = -1; | ||
srand(time(0)); // Ðàñêðóòêà ãåíåðàòîðà ñëó÷àéíûõ ÷èñåë | ||
} | ||
|
||
int Quoter::lastQuote() const { | ||
return lastquote; | ||
} | ||
|
||
const char* Quoter::quote() { | ||
static const char* quotes[] = { | ||
"Are we ahving fun yet?", | ||
"Doctor always know best", | ||
"Is it ... Atomic?", | ||
"Fear is obscene", | ||
"There is no scientific evidence", | ||
"to support the idea", | ||
"that life is serious", | ||
"Things that make us happy, make us wise", | ||
}; | ||
const int qsize = sizeof quotes / sizeof *quotes; | ||
int qnum = rand() % qsize; | ||
|
||
while (lastquote >= 0 && qnum == lastquote) | ||
qnum = rand() % qsize; | ||
return quotes[lastquote = qnum]; | ||
} | ||
|
||
int main() { | ||
Quoter q; | ||
const Quoter cq; | ||
cq.lastQuote(); // Ìîæíî | ||
//! cq.quote(); // Íåëüçÿ: íåêîíñòàíòíàÿ ôóíêöèÿ | ||
for (int i = 0; i < 20; i++) | ||
cout << q.quote() << endl; | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
//: C08:Safecons.cpp | ||
// Использование const для защиты данных | ||
#include <iostream> | ||
using namespace std; | ||
|
||
const int i = 100; // Типичная константа | ||
const int j = i + 10; // Значение константного выражения | ||
long address = (long)&j;// Требует выделения памяти | ||
char buf[j + 10]; // Также константное выражение | ||
|
||
int main() { | ||
cout << "type a character & CR:"; | ||
const char c = cin.get(); // Изменение невозможно | ||
const char c2 = c + 'a'; | ||
cout << c2; | ||
//... | ||
} ///:~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
//: C08:StringStack.cpp | ||
// Èñïîëüçîâàíèå static const äëÿ ñîçäàíèÿ | ||
// êîíñòàíò âðåìåíè êîìïèëÿöèè â êëàññå | ||
#include <string> | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class StringStack { | ||
static const int size = 100; | ||
const string* stack[size]; | ||
int index; | ||
public: | ||
StringStack(); | ||
void push(const string* s); | ||
const string* pop(); | ||
}; | ||
|
||
StringStack::StringStack() : index(0) { | ||
memset(stack, 0, size * sizeof(string*)); | ||
} | ||
|
||
void StringStack::push(const string* s) { | ||
if (index < size) | ||
stack[index++] = s; | ||
} | ||
|
||
const string* StringStack::pop() { | ||
if (index > 0) { | ||
const string* rv = stack[--index]; | ||
stack[index] = 0; | ||
return rv; | ||
} | ||
return 0; | ||
} | ||
|
||
string iceCream[] = { | ||
"pralines & cream", | ||
"fudge ripple", | ||
"jamocha almond fudge", | ||
"wild mountain blackberry", | ||
"raspberry sorbet", | ||
"lemon swirl", | ||
"rocky road", | ||
"deep chocolate fudge" | ||
}; | ||
|
||
const int iCsz = sizeof iceCream / sizeof *iceCream; | ||
|
||
int main() { | ||
StringStack ss; | ||
for (int i = 0; i < iCsz; i++) | ||
ss.push(&iceCream[i]); | ||
const string* cp; | ||
|
||
while ((cp = ss.pop()) != 0) | ||
cout << *cp << endl; | ||
} ///:~ |
Oops, something went wrong.