Reference: wk智云回放 CS 106L学不明白了(悲)

Lec 1

:::info

  • string在C++里是一个类,区别于int
  • name.length()可以计算字符串的长度
  • name + "Kenshin"strcat的功能
  • name.substr(pos, n),第一个参数是起始位置,第二个是字符数
  • 内存分配new``delete
    • int* p = new int;``int* q = new int[10];
    • delete p;``delete[] q; :::

Lec 2

Reference

并不是oop独有的概念

:::info

  • char& r = c; //initialize本地变量的引用必须在声明时初始化
    • 引用可以看做别名
    • 这种别名的绑定在程序运行期间是一直存在的且不可更改的
    • 函数传入引用作为参数void func(type& var);
    • Restrictions
      • No reference to reference
      • No pointer to reference
      • Reference to pointer is OK
      • No array of references
  • 在一些函数里,我们并不希望传入的指针所指向的变量被函数所影响,于是我们可以这样写
    • void func(**const **type* p);
  • 声明定义

    • 声明 ( declaration ) 表示“存在这样一个东西”,编译器只是记录,定义 ( definition ) 表示“这个东西是什么”
    • struct {int x, y;};其本身和成员变量都算声明 :::

      Class引入

      :::info
  • 的概念

  • this指针引入
    • wk:“所有的普通的成员函数都有一个隐藏的参数,是它参数表里的第一项,是c++编译器的语法糖,而这个参数就叫this,是这个结构体的指针”。
    • 因此,使用.运算符的时候, a.Print()实际上是Print(&a)
  • classstruct基本一样,唯一的不同在于访问权限
  • 在C++中,可以使用private:public:来标识哪些是私有的,哪些是公开的
    • 一般来说,数据成员是私有的,方法是公开的
    • ::范围解析运算符 ( resolver )
      • <class name>::<func name>
      • ::<func name>
  • 对象是属性+服务 ::: 面向对象程序设计 - 图2 :::info

  • 对象的关系:类是对象的抽象,对象是类的实例 ::: 这是一个简单的例子 ```cpp

    include

    using namespace std;

class Position { private: pair pos; // public: void printPos(); void updatePos(pairnewPos); };

void Position::printPos() { cout << “Position is: “; cout << “(“ << this->pos.first << “, “ << this->pos.second << “)” << endl; }

void Position::updatePos(pair newPos) { this->pos = newPos; }

int main() { Position a; a.updatePos(pair(1,2)); a.printPos(); return 0; }

//输出 //Position is: (1, 2)

  1. <a name="i9sAB"></a>
  2. ### `::`resolver
  3. :::info
  4. - `<class name>::<func name>`表示`func name`不自由,属于`class name`
  5. - `::<func name>`表示`func name`是全局变量中的自由函数
  6. - 变量同理
  7. :::
  8. :::info
  9. - 类的静态变量 ( static )**属于类**而**不属于实例**,不能通过一般的方式初始化,可以通过`::`在全局范围内初始化。在访问静态变量时,始终推荐使用`class name::staticVar`的方式访问静态变量_(_[_参考了xx_](https://www.yuque.com/xianyuxuan/coding/cpp-oop#5TeQ9)_)_
  10. :::
  11. ```cpp
  12. #include <iostream>
  13. using namespace std;
  14. class Position {
  15. private:
  16. //static int type = 1; //不能把静态变量的初始化放置在变量定义中
  17. static int type;
  18. public:
  19. static int getType(){return type;}
  20. };
  21. int Position::type = 1; //初始化静态变量,不能加static!
  22. int main() {
  23. Position a;
  24. //cout << a.getType() << endl; //实际上转化为了下面对类的访问
  25. cout << Position::getType() << endl;
  26. }

Stash

:::info

  • Container
    • 存放对象的容器
  • Stash一般是指typeless的container,可以扩大 :::

Lec 3

Class & Object

:::info

  • OOP Characteristics
    • A program is a bunch of objects telling each other what to do by sending messages
      • 是“做什么”而不是“怎么做”
      • 是发送请求“要做什么”而不是“好为人师”的指点
    • “其实oop的核心就是封装,继承,多态” :::

      C’tor & D’tor | 构造函数 & 析构函数

      成员函数中比较特殊的是C’tor ( constructor ) D’tor ( destructor )

      C’tor

      ```cpp class X{ private: int x, y; public: X(int x, int y){ this->x = x; this->y = y; } //其他方法 };

int main(){ X a(1,1); //a.X(1,1) Wrong!!! }

  1. :::info
  2. - 在语法上,要求构造函数名和类的名字**完全相同**,且构造函数没有返回值
  3. - 构造函数在对象被创建时被编译器**隐式调用**,**不能被显式调用_(如line14_**
  4. - 称不需要参数的构造函数为Default C'tor
  5. - 当构造函数未被声明时,存在一个不做任何事的 "Auto Default C'tor",我们认为C++的对象必须存在一个构造函数
  6. - 我们希望每个类都存在一个Default C'tor
  7. - Default C'tor 和 有参数的 C'tor 可以共存
  8. - <eg>`class_name(type var){}`
  9. - <eg>`class_name(){}`
  10. :::
  11. 下面是初始化的例子
  12. ```cpp
  13. #include <iostream>
  14. using namespace std;
  15. class Position {
  16. private:
  17. int x;
  18. int y;
  19. public:
  20. Position(int x,int y) {
  21. this->x = x;
  22. this->y = y;
  23. }
  24. };
  25. int main() {
  26. //general initlization with C'tor
  27. Position a[]{Position(1, 2), Position(3, 4)};
  28. Position b{Position(1,1)};
  29. }

D’tor

:::info

  • 析构函数不能有任何参数
  • 在对象的生命周期即将结束时,析构函数被隐式调用
  • 通常在析构函数里做的事情是处理除内存以外的资源,如关闭打开的文件 ::: ```cpp

    include

    using namespace std;

class Test { int id; public: Test(int i) { id = i; } ~Test() { cout << “ID: “ << id << “ destruction function is invoked!” << endl; }; };

int main() { Test t0(0); //栈中分配
Test t1[3]{1, 2, 3}; //栈中分配,数组型对象 Test t2 = new Test(4); //堆中分配 delete t2; Test t3 = new Test[3]{5, 6, 7}; //堆中分配 delete[]t3; cout << “———End of Main———-“ << endl; return 0; }

/ ID: 4 destruction function is invoked! ID: 7 destruction function is invoked! ID: 6 destruction function is invoked! ID: 5 destruction function is invoked! ———End of Main———- ID: 3 destruction function is invoked! ID: 2 destruction function is invoked! ID: 1 destruction function is invoked! ID: 0 destruction function is invoked! /

  1. <a name="MfM2h"></a>
  2. ### Some Tips
  3. <a name="NH6qo"></a>
  4. #### Definition of Class
  5. :::info
  6. - 声明放在`.h`里,函数的主体放在`.cpp`里
  7. - 在类外定义时,需要范围解析运算符`::`,方法参见[这里](#i9sAB)
  8. - 在类内定义时,函数默认被`inline`**内联函数**所修饰 [🔗**_( detail )_**](https://www.yuque.com/xianyuxuan/coding/cpp-oop#1wQNV)
  9. - 主要作用是在函数优化上,是**空间换时间的做法**,适用于短小且频繁使用的代码,编译器会将函数内容贴在调用函数的地方来减少栈消耗
  10. - 一般不采用这种写法
  11. - **Compile unit**
  12. - A `.cpp`file is a compile unit
  13. :::
  14. <a name="YJM0c"></a>
  15. #### 标准头文件结构
  16. ```cpp
  17. #ifdef HEADER_NAME
  18. #define HEADER_NAME
  19. //...
  20. #endif //HEADER_NAME

:::info

  • Abstract | 抽象
    • “拨云见日”的能力——ignore details and focus on high level
    • “庖丁解牛”的能力——dividing a whole into well-defined parts
  • TDD | 测试驱动开发 :::

Lec 4

Container | 容器

:::info

  • STL | Standard Template Library
    • 🔗Sequence Containers
    • 🔗Associative Containers
    • “00年时我们在奉节做过一个项目,用了某大厂的MFC,具体是每打进一个电话就往数据库里写几条记录。当时的机器内存只有64M,而这个MFC在每写入记录后就会吞掉几字节的内存再也不还回来。七天之后,当地的工作人员打电话来说不能正常工作了”(笑)
    • Iterators | 迭代器
      • 可以自增list<int>::iterator ltr = L.begin();``ltr++;
      • 可以解引用*ltr = 10;
      • 可以看做指针 :::

Lec 5

:::info

  • 初始化列表
    • 初始化列表的执行顺序是成员变量的声明顺序type T1,T2,T3;``class_name:T3(1),T2(3),T1(2){}的执行顺序是T1->T2->T3
    • 成员变量初始化方法(按执行先后)(如下程序段)
      1. 构造函数参数表
      2. 定义时赋值
      3. 构造函数函数内部
    • Student::Student(string s):name(s){}——initializationStudent::Student(string s){name = s;}——assignment ,这两者的性能是不一样的
      • ⚠️使用第二种方式时,要求有Default C’tor ::: ```cpp

        include

        include

        using namespace std;

string flag{“Global Var”};

class Test { private: string flag = “2”; public: Test() : flag(“1”) { this->flag = “3”; } void Print() { cout << flag << endl; } };

int main() { Test t; t.Print(); return 0; }

//输出 / 3 //如果注释掉第13行,输出1, //如果取消第12行的参数列表,输出2 /

  1. <a name="Clx1P"></a>
  2. ## Overload | 重载
  3. :::info
  4. - **Overload | 重载**
  5. - `void print(string str);`
  6. - `void print(double r, int width);`
  7. - etc
  8. - **函数名可以相同**但**参数表不同**
  9. - 重载**不支持**自动类型转换
  10. - `void func(int a)``void func(double a)`,调用`func(1.1)`**不会**取整为1
  11. :::
  12. <a name="OthXp"></a>
  13. ## Default Argument | 默认参数
  14. :::info
  15. - format
  16. - `void func(int a = 1);`
  17. - `void func(int a, int b, int c = 1);`
  18. - `void func(int a, int c = 1, int b);`非法
  19. - 省略参数时,按default argument赋值,传入参数时,按传入参数赋值
  20. - **有**默认值的参数必须位于**没有默**认值参数**之后**
  21. - 若同时有函数声明和者函数体,默认参数只能写在其中一个里
  22. :::
  23. <a name="PUlhY"></a>
  24. ## C++ Access Control
  25. :::info
  26. - C++通过标签来控制权限
  27. - `public`公有成员
  28. - `private`私有成员
  29. - `protected`受保护的成员
  30. - `friend`友元
  31. :::
  32. <a name="kD9e3"></a>
  33. ### `protected`
  34. :::info
  35. - 没有继承的情况下,`protected`和`private`相同
  36. - `protected`的可访问范围比`private`大,比`public`小
  37. :::
  38. ![](https://cdn.nlark.com/yuque/0/2022/jpeg/22181361/1642687310207-e9d00fa9-0210-4000-801b-f5c6b222ffe0.jpeg)
  39. :::info
  40. - 基类的`protected`可以在派生类的**作用域内**被访问
  41. - [🔗](http://c.biancheng.net/view/252.html)详解
  42. :::
  43. ```cpp
  44. using namespace std;
  45. class Base {
  46. private:
  47. int nPrivate;
  48. public:
  49. int nPublic;
  50. protected:
  51. int nProtected;
  52. };
  53. class Derived :public Base {
  54. void AccessBase() {
  55. nPublic = 1; //OK
  56. //nPrivate = 1; //错,不能访问基类私有成员
  57. nProtected = 1; //OK 访问从基类继承的protected成员
  58. //上面三行访问的实际上是this指针所指向的对象
  59. Derived a;
  60. a.nProtected = 1; //OK
  61. a.nPublic = 1; //OK
  62. Base b;
  63. //b.nProtected = 1; //错 此时并不在派生类作用域里
  64. b.nPublic = 1; //OK
  65. }
  66. };
  67. int main() {
  68. Base c;
  69. Derived d;
  70. //c.nProtected = 1; //错 不在派生类作用域内
  71. //d.nProtected = 1; //错 不在派生类作用域内
  72. d.nPublic = 1; //OK
  73. return 0;
  74. }

friend

:::info

  • 类的友元定义在类的外部,但有权访问类内的privateprotected
  • 友元可以是
    • 函数
    • 类,其所有成员皆是友元
  • 友元关系不可传递,即类 A 是类 B 的友元,类 B 是类 C 的友元,并不能导出类 A 是类 C 的友元 ::: ```cpp class Student{ private: int id; friend class Grade;

public: friend void printID(Student student) { cout << student.id << endl; //可以访问private } };

class Grade{ Student student; public: void func() { student.id = 1; //可以访问private printID(student); //可以访问private } };

  1. <a name="BCpAg"></a>
  2. ## Inline Function | 内联函数
  3. > [🔗](#NH6qo)See Here
  4. :::info
  5. **内联函数inline:**引入内联函数的目的是为了解决程序中函数调用的效率问题。程序在编译的时候,编译器将程序中出现的内联函数的调用表达式用内联函数的函数体进行替换,而对于其他的函数,都是在运行时候才被替代。这其实就是个空间代价换时间的节省。所以内联函数一般都是1-5行的小函数。在使用内联函数时要注意:
  6. - 在内联函数内不允许使用循环语句和开关语句
  7. - 内联函数的定义必须出现在内联函数第一次调用之前
  8. - 类结构中内部定义的函数是内联函数
  9. :::
  10. :::warning
  11. - 和宏的区别与联系
  12. - 做法相似,但宏只是简单地文本替换,内联可以做函数做的事
  13. - 内联函数的声明和定义必须在同一个编译单元里,否则无法编译
  14. :::
  15. <a name="FvVPK"></a>
  16. # Lec 6
  17. <a name="uc9h9"></a>
  18. ## `const`
  19. <a name="YVpqy"></a>
  20. ### const variables & pointers
  21. “C++对`const`的变量的保护只在编译时”
  22. :::info
  23. - 修饰局部变量
  24. - `const int x = 1;``int const x = 1;`两种写法一样
  25. - 修饰指针
  26. - `const int* px = &a;``int const* px = &a;`**常量指针**
  27. - 不能通过`*px = 1`的方式来改变指针指向的值
  28. - 可以间接地通过引用的对象被改变`a = 1`
  29. - 可以指向别的地址`px = &b`
  30. - `int* const px = &a;`**指针常量**
  31. - 指针常量指向的地址不能改变
  32. - 可以通过这个指针来修改值`*p = 1`
  33. - `const int* const px = &a;`**指向常量的常指针**
  34. - 指向的地址不能改变,也不能通过这个指针来修改变量的值
  35. - ⚠️区分**常量指针**和**指针常量**的关键在于`*`的位置,我们以`*`为分界线,如果`const`在`*`的**左边**,则为常量指针,如果`const`在`*`的**右边**则为指针常量。如果我们将`*`读作“指针”,将`const`读作“常量”的话,则`const int* px`是常量指针,`int const* px`是指针常量。
  36. :::
  37. 大型结构作为参数传入函数时,更好的做法是传一个指针,为了避免错误的修改,用`const`修饰传入的指针<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/22181361/1642748439892-750d2335-b91b-41be-9f83-bc9929db514c.png#clientId=u1e564561-58b8-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=384&id=u0c971d3f&margin=%5Bobject%20Object%5D&name=image.png&originHeight=767&originWidth=1143&originalType=binary&ratio=1&rotation=0&showTitle=false&size=383016&status=done&style=none&taskId=u52efca49-43c5-42b7-b83d-44ea44200fc&title=&width=571.5)
  38. <a name="jmLk1"></a>
  39. ### const objects
  40. 当一个对象被`const`修饰时,只有不修改成员变量值的那些函数才可以被调用,C++的做法是使用`const`修饰这些函数<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/22181361/1642748913439-46563283-f0d1-42b5-a5fd-e0e3d17f93a0.png#clientId=u1e564561-58b8-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=245&id=u19a07ba0&margin=%5Bobject%20Object%5D&name=image.png&originHeight=835&originWidth=1252&originalType=binary&ratio=1&rotation=0&showTitle=false&size=437838&status=done&style=none&taskId=u83849ec2-13cd-4f12-9910-8e3ffd8c4ed&title=&width=367)![image.png](https://cdn.nlark.com/yuque/0/2022/png/22181361/1642749002094-62cba629-4682-4fff-ab52-d173a30dd0f7.png#clientId=u1e564561-58b8-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=245&id=u78363f8f&margin=%5Bobject%20Object%5D&name=image.png&originHeight=858&originWidth=1303&originalType=binary&ratio=1&rotation=0&showTitle=false&size=563424&status=done&style=none&taskId=ubeb7dd24-3972-4d0d-9b14-aea5e162060&title=&width=372)
  41. :::warning
  42. - 声明和定义处都需要`const`修饰
  43. - 即使用`const`修饰,编译器仍会检查函数内部是否修改了`const`对象的值或者调用了其他没有用`const`修饰的函数
  44. - 用`const`修饰过的成员函数对于const objects更安全
  45. :::
  46. 下面程序段是一个简单的例子
  47. ```cpp
  48. class Student{
  49. private:
  50. int id;
  51. public:
  52. Student(){}
  53. void print() const{
  54. cout << "const_print" << endl;
  55. }
  56. void print(){
  57. cout << "non_const_print" << endl;
  58. }
  59. };
  60. int main() {
  61. const Student student;
  62. student.print(); //调用line6
  63. Student student1;
  64. student1.print(); //调用line9
  65. }
  66. /*
  67. const_print
  68. non_const_print
  69. */

:::info

  • 若类的成员变量被const修饰时,变量必须在初始化列表时被初始化 :::

static

  1. class Position {
  2. private:
  3. //static int type = 1; //不能把静态变量的初始化放置在变量定义中
  4. static int type;
  5. public:
  6. static int getType(){return type;}
  7. //return this->type //Wrong!!!
  8. };
  9. int Position::type = 1; //初始化静态变量,不能加static!
  10. int main() {
  11. Position a;
  12. //cout << a.getType() << endl; //实际上转化为了下面对类的访问
  13. cout << Position::getType() << endl;
  14. }

类的静态变量

:::info

  • 类的静态变量 ( static )属于类不属于实例,不能通过一般的方式初始化,可以通过::在全局范围内初始化。在访问静态变量时,始终推荐使用class name::staticVar的方式访问静态变量参考了xx
  • .cpp里不要使用static( line 10 ),只在类里 (.h)声明即可
  • 参考上面例程 :::

    类的静态函数

    :::info

  • 类的静态函数不再有this指针,也不能直接访问非静态成员或非静态函数 ( line 7 )

  • .cpp里不要使用static( 如line 10,对函数来说一样 ),只在类里 (.h)声明即可 :::

namespace & using

:::info

  • 使用namespace来封装代码 ::: ```cpp //include in “xxx.h” namespace Animals{ class Cat{ public:
    1. void Meow(){cout << "Meow" << endl;}
    }; class Dog{
    1. //something
    }; int GetSpeciesNum(); void ListSpecies(); }

int main() { using namespace Animals; Animals::Dog myDog; Animals::Cat myCat; myCat.Meow(); Animals::ListSpecies(); }

  1. :::info
  2. - 使用`using namespace space_name`后,可以省略`space_name`,但要避免**歧义( Ambiguities )**
  3. - 使用全名访问时总是可以的
  4. :::
  5. ```cpp
  6. namespace X{
  7. void f();
  8. void g();
  9. }
  10. namespace Y{
  11. void g();
  12. void h();
  13. }
  14. int main() {
  15. using namespace X;
  16. using namespace Y;
  17. f();
  18. //g(); //歧义
  19. X::g(); //OK
  20. h();
  21. }

:::info

  • namespace组合( composition ),可以在namespace的里面继续使用namespace
  • 多个namespace同名,在编译时会被合为一个namespace :::

Lec 7

Inheritance | 继承

“‘继承’是C++代码复用的一种手段,拿一个已有的类去定义新的类。区别于‘组合’在类里构造新对象”。

  • “Inheritance is to take existing class, clone it, and then make additions and modifications to the clone”
    • 从这个定义来看继承有“遗传”的意思,而modifications和additions可以理解为“变异”。

面向对象程序设计 - 图3

  • “The ability to define the behavior or implementation of a class as a superset(超集)of another set”

面向对象程序设计 - 图4

“接口的重用——继承 (inheritance)。我们定义了“人类”这个类,有时我们需要更细致的划分。例如我们需要“学生”这样一个类。显然,“学生”是“人类”的真子集,因此“学生”这个类必然拥有“人类”的状态和行为。也就是说,“人类”具有的接口在“学生”中都能找到。而不同的是,“学生”作为一个更细的划分,具有一些“人类”不一定具有的状态和行为,例如均绩和交作业。“人类”是比“学生”更为抽象的一个概念。 那么,“学生”作为一个新的类,将“人类”的接口拷贝一份当然是可以达到要求的,但是这将大幅降低设计的效率和模型的可维护性。因此我们引入了继承这一机制。继承可以让我们克隆一个(或多个)已经存在的类的状态和行为,并在克隆的基础上进行一些增加或修改,从而获得我们需要的类。我们将原来的类称为基类超类父类,新的类称为派生类继承类子类”

基本用法

:::info

  • 语法一般是class DerivedClassName:access-specifier BaseClass1Name, access-specifier BaseClass2Name, ...
    • 这里访问修饰符access-specifierprivate, public, protected中的一个(🔗protected访问范围)
    • 不加访问修饰符,则默认为private
    • BaseClass 是基类的名字,DerivedClass 是继承类的名字
  • 不同类型的继承

    • **public**:基类的public也是派生类的public,基类的protected也是派生类的protected,基类的private不能被派生类直接访问。但是可以通过调用基类的公有和保护成员来访问(即这个变量仍然存在于子类的内存中,但是不能由子类直接访问)
    • **protected**:基类的publicprotected将成为派生类的protected
    • **private**:基类的publicprotected将成为派生类的private
    • 我们几乎不使用 protected 或 private 继承,通常使用 public 继承 ::: ```cpp class Base { private: int privateVar; protected: int protectedVar; public: int publicVar;

      Base() : privateVar(1), publicVar(2), protectedVar(3) {} void Print() { cout << “privateVar: “ << privateVar << endl; cout << “publicVar: “ << publicVar << endl; cout << “protectedVar: “ << protectedVar << endl; cout << “———-“ << endl; } void Modify() { srand(time(NULL)); privateVar = rand() % 10; publicVar = rand() % 10; protectedVar = rand() % 10; } };

class Derived:public Base { public: void DerivedModify(){ srand(time(NULL)); //privateVar = rand() % 10; //Wrong!!! 只能通过基类的函数访问private publicVar = rand() % 10; protectedVar = rand() % 10; } };

int main() { Base base; base.Print(); Derived derived; derived.Modify(); derived.Print(); derived.DerivedModify(); derived.Print(); }

  1. :::info
  2. - 子类**不继承父类的构造函数、析构函数和**[**🔗**](#NaAzp)**重载运算符**。在创建一个子类对象时,如果没有明确指出,则子类对象构造时会首先调用父类的构造函数
  3. :::
  4. ```cpp
  5. class Base {
  6. public:
  7. Base(){cout<< "Base()" << endl;}
  8. ~Base(){cout<< "~Base()" << endl;}
  9. };
  10. class Derived:public Base {
  11. public:
  12. Derived(){cout << "Derived()" << endl;}
  13. ~Derived(){cout << "~Derived()" << endl;}
  14. };
  15. int main() {
  16. Derived derived;
  17. }
  18. /*
  19. Base()
  20. Derived()
  21. ~Derived()
  22. ~Base()
  23. */

:::info

  • 在父类没有 Default C’tor 时,子类需要显式的初始化父类,可使用参数列表 (line9) ::: ```cpp class Base { public: Base(int x){cout<< “Base()” << endl;} //~Base(){cout<< “~Base()” << endl;} };

class Derived:public Base { public: Derived():Base(1){cout << “Derived()” << endl;} //~Derived(){cout << “~Derived()” << endl;} };

  1. <a name="pAzc1"></a>
  2. ### Name Hide | 名字隐藏
  3. :::info
  4. - **名字隐藏**是指父类中有一组重载函数,子类在继承父类时如果覆盖了这组重载函数中的任意一个,则其余没有被覆盖的同名函数在子类中是不可见的
  5. - **解决方案**
  6. - 可以在子类中不使用覆盖函数,而是给子类的方法选择一个不同的函数名以区别于父类的方法
  7. - 另一种解决方案是子类覆盖父类中所有的重载方法,虽然子类中有些方法的实现与父类完全一致,但是这样做的好处是不会增加新的函数名
  8. :::
  9. ```cpp
  10. class Base {
  11. public:
  12. void Print(){cout <<"void_print" << endl;}
  13. void Print(string s){cout << "string_print: " << s << endl;}
  14. void Print(double x){cout <<"double_print: " << x << endl;}
  15. };
  16. class Derived:public Base {
  17. public:
  18. void Print(string s){
  19. Base::Print(s);
  20. }
  21. };
  22. int main() {
  23. Derived derived;
  24. derived.Print("Hello World");
  25. //derived.Print(1.1); //Wrong!!!
  26. //derived.Print(); //Wrong!!!
  27. }

🔗虚继承

先来看这样一段代码

  1. class Base {
  2. private:
  3. int a = 1;
  4. };
  5. class Derived:public Base {
  6. private:
  7. int a = 2;
  8. int b = 3;
  9. public:
  10. void Print(){cout << a << endl;}
  11. };
  12. int main() {
  13. Derived derived;
  14. int *ptr = (int *) &derived;
  15. derived.Print();
  16. cout <<"---" << endl;
  17. for (int i = 0; i < sizeof(derived) / sizeof(int); i++) {
  18. cout << ptr[i] << endl;
  19. }
  20. }
  21. /*
  22. 2
  23. ---
  24. 1
  25. 2
  26. 3
  27. */

子类和父类中有同名的a,但打印出的却是子类的a,并且通过后续的打印看出子类中的确继承了父类的a,这是为什么呢?

摘自xyx

1 C++面向对象

向上整型 | upcast

  1. class Base {...};
  2. class Derived:public Base {...};
  3. int main() {
  4. Derived derived;
  5. Base base = derived; //slice
  6. Base *basePtr = &derived; //upcast
  7. Base &baseRef = derived; //upcast
  8. }

:::info

  • 将子类的对象向上整型为一个父类的对象,这总是可以做到的,因为子类包含父类的所有对象和方法,但是子类特有的成员会丢失 :::

Lec 8

多态 | Polymorphism

虚函数 & 纯虚函数

  1. class Shape{
  2. protected:
  3. Point center;
  4. public:
  5. virtual void Render() {} //dynmaic binding
  6. void Move(){} //static binding
  7. };
  8. class Rectangle:public Shape {
  9. protected:
  10. int width, height;
  11. public:
  12. void virtual Render() { cout << "..." << endl << "..." << endl; }
  13. };
  14. class Square:public Shape {
  15. public:
  16. void virtual Render() { cout << ".." << endl << ".." << endl; }
  17. };
  18. int main() {
  19. Rectangle r;
  20. Square s;
  21. Shape* ptr = &r;
  22. ptr->Render();
  23. }
  24. /*
  25. ...
  26. ...
  27. */

:::info

  • 虚函数是在基类中使用关键字virtual声明的函数。在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数
  • 如例程,此时父类和子类的Render()存在 Override 的关系
    • 参数表要相同才可构成 Override 关系
    • Name Hide 依旧存在,子类需要 Override 父类的所有重载函数 :::

“我们可以通过 virtual Type functionName( Parameter List ) = 0; 来定义一个 纯虚函数。当我们想要在基类中定义虚函数,以便在派生类中重新定义该函数更好地适用于对象,但在基类中又不能对虚函数给出有意义的实现,这个时候就会用到纯虚函数”

:::info

  • 一旦类中有一个纯虚函数 ( pure virtual function ),这个类就成为了抽象类。抽象类不能创建对象 :::

🔗How virtual works

面向对象程序设计 - 图5
面向对象程序设计 - 图6
面向对象程序设计 - 图7
面向对象程序设计 - 图8 :::info

  • 每个有虚函数的类都有一个 v-ptr ,指向这个类的 v-table 。v-table 里记录了这个类里所有虚函数的地址(函数指针)
  • v-ptr在构造函数里被唯一的初始化,在后续操作中均不改变
  • 对虚函数的调用可以归结为pObj->v_ptr->v_table[]
  • v-table 内指针顺序不可改变 :::

    静态绑定 & 动态绑定

    :::info

  • 静态绑定 | static binding

    • 发生在编译时刻,又称早绑定( early binding )
    • 编译器能够明确知道是哪个类的方法
  • 动态绑定 | dynamic binding
    • 发生在运行时刻,又称晚绑定( late binding )
    • virtual关键字声明且通过指针访问的为动态绑定 :::

接口(抽象类)

接上面,由于继承的存在,一些类可以用于去规范派生类的行为,而不用于实例化对象。这样的类被称为抽象类( Abstract Class ),也称为接口( Interface )

Lec 9

image.png
2是对的,为了兼容老版本 C 而保留

拷贝构造 | Copy C’tor

:::info

  • 形式上,拷贝构造函数是class_name(**const** class_name& r){}
  • 拷贝构造发生在如**class_name obj1 = obj2;**``**func(obj);**``**class_name obj1 = func(obj2);**的情况下。当传入参数为对象时,会在函数内部复制一个临时的对象,此时会发生拷贝构造。但要注意一点,在函数返回发生拷贝构造时要注意可能会发生优化,可能不会发生拷贝构造。隐式的拷贝构造还发生在将对象放入容器中时,如**vector<class_name> vec{obj1,obj2};**
  • 区分拷贝构造和赋值的区别(只有C++有给对象赋值的概念,原因是这一定程度上违背了封装的原则)
  • 当没有拷贝构造函数时,会调用默认拷贝构造函数,即直接复制所有成员。但对于指针来说会导致错误,如下图及例程

image.png :::

  1. class A{
  2. char *str;
  3. public:
  4. //A(const A&){}
  5. A(const char *s) {
  6. str = new char[strlen(s) + 1];
  7. strcpy(str, s);
  8. }
  9. ~A() {
  10. delete[]str;
  11. }
  12. };
  13. int main(){
  14. A p1("Hello");
  15. A p2 = p1; //发生拷贝构造
  16. //调用析构函数,先delete p2再delete p1,
  17. //但p1 p2指向的是同一块内存,发生错误
  18. }

一个正确的例程如下:

  1. static int counter = 0;
  2. class Array{
  3. int *pInt;
  4. int size;
  5. public:
  6. Array() {
  7. counter++;
  8. size = 1;
  9. pInt = new int;
  10. cout << "default c'tor...address: " << &pInt
  11. << ", current obj: " << counter << endl;
  12. }
  13. Array(int size) {
  14. counter++;
  15. this->size = size;
  16. pInt = new int(size);
  17. cout << "c'tor...address: " << &pInt
  18. << ", current obj: " << counter << endl;
  19. }
  20. Array(const Array& obj) { //copy c'tor
  21. counter++;
  22. pInt = new int(obj.size);
  23. *pInt = *(obj.pInt);
  24. cout << "copy c'tor...address: " << &pInt
  25. << ", current obj: " << counter << endl;
  26. }
  27. ~Array() {
  28. counter--;
  29. cout << "deleted...address: " << &pInt
  30. << ", current obj: " << counter << endl;
  31. delete pInt;
  32. }
  33. };
  34. Array& func(Array obj) {
  35. cout << "--func invoked--" << endl;
  36. cout << "--end of func--" << endl;
  37. return obj;
  38. }
  39. int main(){
  40. Array arr1;
  41. Array arr2(2);
  42. Array arr3(arr2);
  43. func(arr2);
  44. return 0;
  45. }
  46. /*
  47. default c'tor...address: 0x61fdf0, current obj: 1
  48. c'tor...address: 0x61fde0, current obj: 2
  49. copy c'tor...address: 0x61fdd0, current obj: 3
  50. copy c'tor...address: 0x61fe00, current obj: 4
  51. --func invoked--
  52. --end of func--
  53. deleted...address: 0x61fe00, current obj: 3
  54. deleted...address: 0x61fdd0, current obj: 2
  55. deleted...address: 0x61fde0, current obj: 1
  56. deleted...address: 0x61fdf0, current obj: 0
  57. */

:::success

  • 可以看出 line 45 调用了拷贝构造函数
  • line 46 调用func后,由于传入参数为 Array 对象,也调用了拷贝构造函数,在函数返回后调用析构函数 :::

    Overload Operators | 重载运算符

    可重载的运算符

    image.pngimage.png :::success

  • Restrictions

    • 只能重载已有运算符
    • 只能在自定义的类(结构)中重载运算符
    • 不能改变运算符的目数
    • 不能改变优先级 :::

      成员函数形式的运算符重载

      ```cpp class Point { double x, y; public: Point() {}; Point(double x, double y) { this->x = x, this->y = y; } const Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); } const Point operator+(const Point &p) const { return Point(x + p.x, y + p.y); } void Print() { cout << “(“ << x << “,” << y << “)” << endl; } void Print(Point p) { cout << “(“ << p.x << “,” << p.y << “)” << endl; } };

int main() { Point p(1, 2);

  1. p = p + Point(1,2);
  2. p.Print();
  3. p = p - p;
  4. p.Print(p);

} / (2,4) (0,0) /

  1. :::success
  2. - 返回值为`const Point`是为了避免运算结果被当做左值使用,即避免`p + Point(1,2) = p;`的出现
  3. - `+`为双目运算符,但参数只需要显式的写出一个,另一个为`this`
  4. - 成员运算符重载后**存在隐式类型转换**,但一般一般以**运算符左侧(receiver)**的类型为目标类型
  5. :::
  6. <a name="eYTbA"></a>
  7. ### 全局函数形式的运算符重载
  8. 考虑到需要访问类的私有成员变量,一般全局函数形式的运算符重载需要在类里**声明为友元,**或者类已经提供了访问私有成员变量的方法。
  9. ```cpp
  10. class Point {
  11. double x, y;
  12. public:
  13. Point() {};
  14. Point(double x, double y) {
  15. this->x = x, this->y = y;
  16. }
  17. friend const Point operator-(const Point &left, const Point &right);
  18. friend const Point operator+(const Point &left, const Point &right);
  19. void Print() {
  20. cout << "(" << x << "," << y << ")" << endl;
  21. }
  22. void Print(Point p) {
  23. cout << "(" << p.x << "," << p.y << ")" << endl;
  24. }
  25. };
  26. const Point operator-(const Point &left, const Point &right) {
  27. return Point(left.x - right.x, left.y - right.y);
  28. }
  29. const Point operator+(const Point &left, const Point &right) {
  30. return Point(left.x + right.x, left.y + right.y);
  31. }

:::success

  • line10, 11声明为友元,且操作数需要设置为两个 :::

    运算符重载策略

    image.png :::success

  • 单目( Unary )运算符尽量做成成员

    • **=**``**()**``**[]**``**->**``**->***必须作为成员
  • 双目运算符尽量做成全局
  • ()是指通过指针调用函数 :::

运算符重载规范

image.png :::success

  • 不修改操作数的值,以const &传入 ::: image.png

    部分运算符原型

    image.png :::success

  • 第三条E是指索引元素类型,T是类。如vector<string> v;,对于v[i]EstringTvector<string>

    • 参数 index 可以突破int的限制做成其他类型 :::

      自增/自减运算符重载

      面向对象程序设计 - 图17 :::success
  • 这两个运算符既可以出现在操作数前 ( prefix ),又可以出现在操作数后 ( postfix )。为了区别这两种情况,编译器会在 postfix 时传递一个参数 (int) 0 作为标记 ::: image.png :::success

  • ++(*this);不写为*this += 1;的原因是,在以后修改成员变量时,只需要修改一处*this += 1;,这样其他地方也被一并修改 :::

    关系运算符重载

    image.png
    image.png
    image.png :::success

  • 可以基于已有的关系定义新的关系,不等于基于等于定义 :::

    下标运算符重载

    image.png

    输入输出流重载

    >> & <<

    image.png :::success

  • 必须是有两个参数的非成员函数

  • 模板必须是**istream& operator>>(istream& is, class_name& obj);**cin >> a >> b;的实现其实就是cin >> a的结果还是cin,副作用是向a写入一个值,因此可以“串起来”读入值 ::: image.png

    自定义控制符
    1. // define your own manipulators
    2. // skeleton for an output stream manipulator
    3. ostream &manip(ostream &out){
    4. // ... do something
    5. return out;
    6. }
    7. //

    operator=

    1 C++面向对象
    image.png :::success

  • 为了避免obj = obj;这样的赋值出现导致delete出现错误 ::: :::danger

  • 到目前为止,我们一定要写的函数有:

    • 默认构造函数 Default C’tor
    • 拷贝构造函数 Copy C’tor
    • 赋值运算符重载 =
    • virtual修饰的析构函数 :::

      Lec 10

      自动类型转换 | User-defined Type Conversions

image.pngimage.png :::success

  • 上述情况会用"abc"制造PathName的对象,然后再做赋值,但拷贝构造可能和重载的赋值运算符发生冲突。使用explicit关键字允许拷贝构造而不允许以赋值形式的类型转换 ::: 更为通用的写法是:
    image.png
    image.png
    image.png :::success

  • 语法是class_name1 operator class_name2()

    • class_name1的对象转为class_name2的对象
  • 我们什么时候可以做**T -> C**
    • T中有转化为C的重载,即operator C()存在
    • C中存在利用T的构造,即C(T)存在
    • 上述两种情况只能同时发生一种
    • 由于两种不能同时存在,因此我们引入了explicit保证构造函数不被用于类型转换 :::

函数传参/返回值的Tips

image.png

Left Values & Right Values

image.png

右值引用

image.png
image.png :::info

  • 右值引用的目的是减少拷贝,加速运算 :::

Lec 11

Templates | 模板image.png

Function Templates | 函数模板

  1. template <class T>
  2. void Swap(T &a,T &b) {
  3. T temp = a;
  4. a = b;
  5. b = temp;
  6. }

:::info

  • class可以写作typeT也可以更换
  • 模板又称元 ( meta ) 代码,编译器会将模板实例化来产生新的代码
  • 使用模板时,要求每个实例中的T必须一样 ::: ```cpp template void Func(T &x, T &y){ //… }

//Func(1.0, ‘a’)会报错,模板要求T应一样

  1. :::info
  2. - 函数没有参数但内部会用到`T`时,可以在函数名的后面加上`<type>`来声明
  3. :::
  4. ```cpp
  5. template <class T>
  6. void Func(void){
  7. //...
  8. }
  9. //Func<int>();

Class Templates | 类模板

  1. template <class T>
  2. class MyVector {
  3. private:
  4. T *ptr;
  5. int size;
  6. public:
  7. MyVector(const MyVector &); //copy c'tor
  8. MyVector(int size); //c'tor
  9. MyVector(); //default c'tor
  10. virtual ~MyVector(); //d'tor
  11. MyVector &operator=(const MyVector &); //operator =
  12. };

:::info

  • 模板中的成员函数在类的外部定义时,需要看做函数模板来定义,要声明类,用**<>** ::: ```cpp template MyVector::MyVector(const MyVector &) { //… }

template MyVector& MyVector::operator=(const MyVector &) { //… }

  1. 声明了一个类模板之后,可以这样使用:
  2. ```cpp
  3. MyVector<int> v1(4);
  4. MyVector<string> v2;
  5. MyVector< MyVector<double> >;

:::warning

  • 类模板往往需要重载相应的运算符,否则在编译时可以通过但链接时会报错 ::: :::info

  • 多个类型

image.png

  • 有非类型的参数

image.png

  • template语句属于声明,需要放在.h
    • “一个类模板应该没有对应的.cpp文件才是对的,全部都在头文件里”
    • “大部分情况下,类模板的函数都做成inline
  • 模板与继承
    • 必须实例化模板才能继承

image.png :::

怎么写模板?

image.png

关于友元函数在类模板中声明的问题

这个问题初学的时候确实比较难发现:

Lec 12(摸了)

Exceptions | 异常

Lec 13(摸了)

Lec 14(摸了)

Lec 15

Streams | 流

:::info

  • 一维、单向 ::: 面向对象程序设计 - 图40