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
43
README.md
43
README.md
|
@ -155,36 +155,37 @@ using namespace std;
|
||||||
class Base
|
class Base
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
inline virtual void who()
|
inline virtual void who()
|
||||||
{
|
{
|
||||||
cout << "I am Base\n";
|
cout << "I am Base\n";
|
||||||
}
|
}
|
||||||
virtual ~Base();
|
virtual ~Base() {}
|
||||||
};
|
};
|
||||||
class Derived: public Base
|
class Derived : public Base
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
inline void who() // 不写inline时隐式内联
|
inline void who() // 不写inline时隐式内联
|
||||||
{
|
{
|
||||||
cout << "I am Derived\n";
|
cout << "I am Derived\n";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
// 此处的虚函数who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
|
// 此处的虚函数who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
|
||||||
Base b;
|
Base b;
|
||||||
b.who();
|
b.who();
|
||||||
|
|
||||||
// 此处的虚函数是通过指针调用的,需要在运行时期间才能确定,所以不能为内联。
|
// 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联。
|
||||||
Base *ptr = new Derived();
|
Base *ptr = new Derived();
|
||||||
ptr->who();
|
ptr->who();
|
||||||
|
|
||||||
// 因为Base有虚析构函数,所以调用子类析构函数后,也调用父类析构函数,防止内存泄漏。
|
// 因为Base有虚析构函数(virtual ~Base() {}),所以调用基类(Base)析构函数,也调用派生类(Derived)析构函数,防止内存泄漏。
|
||||||
delete ptr;
|
delete ptr;
|
||||||
ptr = nullptr;
|
ptr = nullptr;
|
||||||
|
|
||||||
return 0;
|
system("pause");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -532,7 +533,7 @@ int main()
|
||||||
{
|
{
|
||||||
Shape * shape1 = new Circle(4.0);
|
Shape * shape1 = new Circle(4.0);
|
||||||
shape1->calcArea();
|
shape1->calcArea();
|
||||||
delete shape1; //因为是虚析构函数,所以调用子类析构函数后,也调用父类析构函数。
|
delete shape1; //因为Shape有虚析构函数,所以delete释放内存时,调用基类析构函数,也调用子类析构函数。
|
||||||
shape1 = NULL;
|
shape1 = NULL;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user