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
71
README.md
71
README.md
|
@ -151,41 +151,42 @@ inline int functionName(int first, int secend,...) {/****/};
|
|||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class Base
|
||||
{
|
||||
public:
|
||||
inline virtual void who()
|
||||
{
|
||||
cout << "I am Base\n";
|
||||
}
|
||||
virtual ~Base();
|
||||
};
|
||||
class Derived: public Base
|
||||
{
|
||||
public:
|
||||
inline void who() // 不写inline时隐式内联
|
||||
{
|
||||
cout << "I am Derived\n";
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
// 此处的虚函数who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
|
||||
Base b;
|
||||
b.who();
|
||||
|
||||
// 此处的虚函数是通过指针调用的,需要在运行时期间才能确定,所以不能为内联。
|
||||
Base *ptr = new Derived();
|
||||
ptr->who();
|
||||
using namespace std;
|
||||
class Base
|
||||
{
|
||||
public:
|
||||
inline virtual void who()
|
||||
{
|
||||
cout << "I am Base\n";
|
||||
}
|
||||
virtual ~Base() {}
|
||||
};
|
||||
class Derived : public Base
|
||||
{
|
||||
public:
|
||||
inline void who() // 不写inline时隐式内联
|
||||
{
|
||||
cout << "I am Derived\n";
|
||||
}
|
||||
};
|
||||
|
||||
// 因为Base有虚析构函数,所以调用子类析构函数后,也调用父类析构函数,防止内存泄漏。
|
||||
delete ptr;
|
||||
ptr = nullptr;
|
||||
|
||||
return 0;
|
||||
}
|
||||
int main()
|
||||
{
|
||||
// 此处的虚函数who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
|
||||
Base b;
|
||||
b.who();
|
||||
|
||||
// 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联。
|
||||
Base *ptr = new Derived();
|
||||
ptr->who();
|
||||
|
||||
// 因为Base有虚析构函数(virtual ~Base() {}),所以调用基类(Base)析构函数,也调用派生类(Derived)析构函数,防止内存泄漏。
|
||||
delete ptr;
|
||||
ptr = nullptr;
|
||||
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### assert()
|
||||
|
@ -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