首页
论坛
课程
招聘
[分享]《探索现代化C++》泛读笔记摘要20 完!
2022-10-2 20:44 5543

[分享]《探索现代化C++》泛读笔记摘要20 完!

2022-10-2 20:44
5543

Chapter 6 面向对象编程

Chapter 6 面向对象编程

基类和派生类

C++11 继承构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class person
{
public:
    explicit person(const string& name):name{name} {}
    //...
};
 
class student
    :public person
{
    using person::person;
};
 
int main()
{
    student tom{"Tom Tomson"};
}

虚函数和多态类

C++11 显示重载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class person
{
    virtual void all_info() const {...}
};
class student
    : public person
{
    virtual void all_info() override {...}
};
 
int main()
{
    student tom("Tom Tomson","Algebra, Analysis");
    person& pr = tom;
    pr.all_info();
}

大型项目会建立多级抽象

  • 接口:无实现
  • 抽象类:默认实现
  • 专门的类

类型转换

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast

高级技术

CRTP 奇异递归模板模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class point
{
public:
    point(int x, int y) :x(x), y(y) {}
    bool operator==(const point& that) const
    {
        return x = that.x && y == that.y;
    }
    bool operator!=(const point& that) const
    {
        return x != that.x || y != that.y;
    }
private:
    int x, y;
};

在命题逻辑和逻辑代数中,德·摩根定律(或称德·摩根定理)是关于命题逻辑规律的一对法则。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
 
using namespace std;
 
template <typename T>
struct inequality
{
    bool operator!=(const T& that) const
    {
        return !(static_cast<const T&>(*this) == that);
    }
};
 
class point:public inequality<point>
{
public:
    point(int x, int y) :x(x), y(y) {}
    bool operator==(const point& that) const
    {
        return x == that.x && y == that.y;
    }
 
private:
    int x, y;
};
 
int main()
{
    point p1(3, 4), p2(3, 5);
    cout << "p1 != p2 is " << boolalpha << (p1 != p2) << '\n';
}

上面的例子在C++20中,也可以不用CRTP。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
using namespace std;
 
class point
{
public:
    point(int x, int y) :x(x), y(y) {}
    bool operator==(const point& that) const = default;
private:
    int x, y;
};
 
int main()
{
    point p1(3, 4), p2(3, 5);
    cout << "p1 != p2 is " << boolalpha << (p1 != p2) << '\n';
}

[2022冬季班]《安卓高级研修班(网课)》月薪三万班招生中~

收藏
点赞0
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回