Skip to content

Commit 73f1d95

Browse files
committed
第一章代码
1 parent 6e30078 commit 73f1d95

File tree

4 files changed

+77
-1
lines changed

4 files changed

+77
-1
lines changed

Effecttive-C++/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
## Effective C++
22

33
1. 视 C++ 为一个语言联邦(C、Object-Oriented C++、Template C++、STL)
4-
2. 宁可以编译器替换预处理器(尽量以 const、enum、inline 替换 #define)
4+
2. 宁可以编译器替换预处理器(尽量以 const、enum、inline 替换 #define)
5+
3. 尽可能使用 const
6+
4. 确定对象被使用前已先被初始化(构造时赋值(copy 构造函数)比 default 构造后赋值(copy assignment)效率高)

Effecttive-C++/term01.cpp

Whitespace-only changes.

Effecttive-C++/term02.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// 尽量使用const enum inline代替#define
2+
3+
// 1. 使用const代替可以保留符号信息 报错时候可以定位到具体的符号 否则只能看到1.635
4+
#define ASPECT_RATION 1.653
5+
const double AspectRatio = 1.653;
6+
7+
// 2.class专属常量
8+
// 类中的静态成员
9+
class GamePlayer {
10+
public:
11+
static int getN() {
12+
return NumTurns;
13+
}
14+
private:
15+
// 常量声明式 如果没有声明初值 一定要有21行的定义式 一定要指定初值
16+
// const int GamePlayer::NumTurns = 0; // 位于实现文件中
17+
// static const int NumTurns;
18+
// 常量声明式 只声明但是没有定义 没有分配内存 实际上在c++11中不用再定义
19+
static const int NumTurns = 5;
20+
// int scores[NumTurns];
21+
};
22+
const int GamePlayer::NumTurns; // NumTurns定义 分配内存
23+
24+
class CostEstimate {
25+
private:
26+
static const double FudgeFactor; // 常量声明位于头文件中
27+
};
28+
const double CostEstimate::FudgeFactor=0; // static class 常量定义 位于实现文件中
29+
30+
#include <iostream>
31+
using std::cout;
32+
using std::endl;
33+
int main() {
34+
// 有访问权限 需要一个静态函数访问
35+
cout << GamePlayer::getN() << endl;
36+
}

Effecttive-C++/term03.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <iostream>
2+
#include <string.h>
3+
4+
class TextBlock {
5+
public:
6+
TextBlock(const char* t){
7+
if(t) {
8+
text = new char[strlen(t)];
9+
strcpy(text, t);
10+
} else {
11+
text = new char[1];
12+
text[0] = '\0';
13+
}
14+
}
15+
~TextBlock() {
16+
delete []text;
17+
}
18+
const char& operator[](std::size_t idx) const {
19+
return text[idx];
20+
}
21+
// 为了避免重复代码 可以通过类型转换的模式实现非const的操作
22+
char& operator[](std::size_t idx) {
23+
// 然后返回的结果是const char& 只能通过const_cast转为非const
24+
return const_cast<char&> (
25+
// 先将对象强制转换为const类型 使用static_cast
26+
static_cast<const TextBlock&>(*this)[idx]
27+
);
28+
}
29+
private:
30+
char* text;
31+
};
32+
33+
int main() {
34+
TextBlock tb("text");
35+
const TextBlock ctb("hello");
36+
std::cout << tb[1] << std::endl;
37+
std::cout << ctb[0] << std::endl;
38+
}

0 commit comments

Comments
 (0)