0%

Cpp 温故而知新.

C++ 特性

多态 Polymorphism 虚函数 Virtual Function 和 纯虚函数 Pure Virtual Function

多态是调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。

虚函数是在基类中使用关键字 virtual 声明的函数。在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数。我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数,这种操作被称为动态链接,或后期绑定

纯虚函数是虚函数,但没有在基类对它给出有意义的实现。包含纯虚函数的类是抽象类,抽象类不能定义实例,但可以声明指向实现该抽象类的具体类的指针引用

有空自己写个例子..

1
2
3
4
5
6
7
8
9
10
11
12
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};

智能指针 Shared_ptr

所谓智能指针,可以从字面上理解为“智能”的指针。具体来讲,智能指针和普通指针的用法是相似的,不同之处在于,智能指针可以在适当时机自动释放分配的内存。也就是说,使用智能指针可以很好地避免“忘记释放内存而导致内存泄漏”问题出现。由此可见,C++ 也逐渐开始支持垃圾回收机制了,尽管目前支持程度还有限。

C++ 智能指针底层是采用引用计数的方式实现的。简单的理解,智能指针在申请堆内存空间的同时,会为其配备一个整形值(初始值为 1),每当有新对象使用此堆内存时,该整形值 +1;反之,每当使用此堆内存的对象被释放时,该整形值减 1。当堆空间对应的整形值为 0 时,即表明不再有对象使用它,该堆空间就会被释放掉。

一些琐碎的知识点

Cpp &

Click here.

fflush()

先看一个例子:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
printf("hello\n");
pid = fork();
if(pid) wait(NULL);
return 0;
}

输出:

KONVxuGZaeY8XJA

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
printf("hello");
pid = fork();
if(pid) wait(NULL);
return 0;
}

输出:

IE5ViefyXqoGaYM

在第二种情况下,父进程和子进程都有一个输出 “hello”,这是因为 “hello” 在 fork() 执行之前就已经在缓冲区中了。这是一个问题。

在第一种情况下,”hello” 只在屏幕上打印一次,因为 printf() 使用行缓冲。一旦到达 “\n”,它就会打印缓冲区中的内容并释放它们。

使用 ffush(),我们可以通过将流的缓冲区中任何未写入的数据写入相关的输出设备来解决这个问题。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
printf("hello");
fflush(stdout);
pid = fork();
if(pid) wait(NULL);
return 0;
}

输出:

UYl9iWT1HGmyKbp

char *p[] and char (*p)[]

char *p[N] is a pointer array which has N pointers, each of them points to the first address of one string.

char (*p)[N] points to an array of N char type variables. The difference between p + 1 and p is sizeof (char p [10]). p + 1 pointes to another array of the same size.

Lambda Expression

[capture](parameters) -> return_type { /* ... */ }