mirror of
https://github.com/huihut/interview.git
synced 2024-03-22 13:10:48 +08:00
修改虚析构函数
This commit is contained in:
parent
9d34787bc1
commit
5ff3ab91ad
11
README.md
11
README.md
|
@ -159,9 +159,9 @@ public:
|
|||
{
|
||||
cout << "I am Base\n";
|
||||
}
|
||||
virtual ~Base();
|
||||
virtual ~Base() {}
|
||||
};
|
||||
class Derived: public Base
|
||||
class Derived : public Base
|
||||
{
|
||||
public:
|
||||
inline void who() // 不写inline时隐式内联
|
||||
|
@ -176,14 +176,15 @@ int main()
|
|||
Base b;
|
||||
b.who();
|
||||
|
||||
// 此处的虚函数是通过指针调用的,需要在运行时期间才能确定,所以不能为内联。
|
||||
// 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联。
|
||||
Base *ptr = new Derived();
|
||||
ptr->who();
|
||||
|
||||
// 因为Base有虚析构函数,所以调用子类析构函数后,也调用父类析构函数,防止内存泄漏。
|
||||
// 因为Base有虚析构函数(virtual ~Base() {}),所以调用基类(Base)析构函数,也调用派生类(Derived)析构函数,防止内存泄漏。
|
||||
delete ptr;
|
||||
ptr = nullptr;
|
||||
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
@ -532,7 +533,7 @@ int main()
|
|||
{
|
||||
Shape * shape1 = new Circle(4.0);
|
||||
shape1->calcArea();
|
||||
delete shape1; //因为是虚析构函数,所以调用子类析构函数后,也调用父类析构函数。
|
||||
delete shape1; //因为Shape有虚析构函数,所以delete释放内存时,调用基类析构函数,也调用子类析构函数。
|
||||
shape1 = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user