运算符“~”在方法旁边时有什么作用?纯虚方法有什么用?
What does the operator '~' do when it is beside a method and what is a pure virtual method for?
示例代码:
#include <string>
namespace vehicle
{
class Vehicle
{
public:
Vehicle(int a);
virtual ~Vehicle(); <------ not method?
protected:
int a;
};
}
此外,我没有完全理解纯虚方法的概念,您将方法声明为:
virtual method() = 0;
我们为什么需要这个?
virtual ~Vehicle();
波浪号 ~
表示析构函数。是一种方法,一种销毁对象的特殊方法。
虚析构函数用于抽象基class。
virtual method() = 0;
那是纯虚函数。它表明您必须为实现此抽象基础 class.
的实现 class 提供实现 method
假设有两个 classes:Base
和 Derived
struct Base
{
Base() {}
virtual void foo() = 0;
virtual ~Base()
{
std::cout << "Base descructor" << std::endl;
}
};
struct Derived : Base
{
int *i;
Derived(int i_): Base(), i(new int[i_]) {}
virtual void foo() override
{
std::cout << "foo" << std::endl;
}
virtual ~Derived()
{
std::cout << "Derived descructor" << std::endl;
delete [] i;
}
};
纯虚函数
如果 Derived
没有覆盖 foo
函数,您可以创建 Derived
class 的实例。当您尝试时,您的代码将无法编译,因为 foo
是一个 纯虚函数 .
error: invalid new-expression of abstract class type 'Derived'
note: because the following virtual functions are pure within 'Derived':
struct Derived : Base
使用纯虚函数来描述接口。
现在关于虚拟析构函数:
The ~
(tilda) sign is used to denote the class destructor. It
is a special method that is called when the object is destroyed.
客户端创建派生实例:
Base *instance = new Derived;
然后以某种方式使用此变量,当您不需要该变量时,您需要释放内存:
delete instance;
让我们追踪调用:
Derived descructor
Base descructor
所以你可以看到基类和派生类的析构函数都被调用了,没有内存泄漏的可能。但是如果你从析构函数中删除这个 virtual
关键字
Base descructor
可以看到Derived的descturtor没有被调用,所以存在内存泄漏(Derived的数组class没有被释放)。
因此,当您通过指针处理对象时,虚拟构造函数很有用。
示例代码:
#include <string>
namespace vehicle
{
class Vehicle
{
public:
Vehicle(int a);
virtual ~Vehicle(); <------ not method?
protected:
int a;
};
}
此外,我没有完全理解纯虚方法的概念,您将方法声明为:
virtual method() = 0;
我们为什么需要这个?
virtual ~Vehicle();
波浪号 ~
表示析构函数。是一种方法,一种销毁对象的特殊方法。
虚析构函数用于抽象基class。
virtual method() = 0;
那是纯虚函数。它表明您必须为实现此抽象基础 class.
的实现 class 提供实现method
假设有两个 classes:Base
和 Derived
struct Base
{
Base() {}
virtual void foo() = 0;
virtual ~Base()
{
std::cout << "Base descructor" << std::endl;
}
};
struct Derived : Base
{
int *i;
Derived(int i_): Base(), i(new int[i_]) {}
virtual void foo() override
{
std::cout << "foo" << std::endl;
}
virtual ~Derived()
{
std::cout << "Derived descructor" << std::endl;
delete [] i;
}
};
纯虚函数
如果 Derived
没有覆盖 foo
函数,您可以创建 Derived
class 的实例。当您尝试时,您的代码将无法编译,因为 foo
是一个 纯虚函数 .
error: invalid new-expression of abstract class type 'Derived'
note: because the following virtual functions are pure within 'Derived':
struct Derived : Base
使用纯虚函数来描述接口。
现在关于虚拟析构函数:
The
~
(tilda) sign is used to denote the class destructor. It is a special method that is called when the object is destroyed.
客户端创建派生实例:
Base *instance = new Derived;
然后以某种方式使用此变量,当您不需要该变量时,您需要释放内存:
delete instance;
让我们追踪调用:
Derived descructor
Base descructor
所以你可以看到基类和派生类的析构函数都被调用了,没有内存泄漏的可能。但是如果你从析构函数中删除这个 virtual
关键字
Base descructor
可以看到Derived的descturtor没有被调用,所以存在内存泄漏(Derived的数组class没有被释放)。
因此,当您通过指针处理对象时,虚拟构造函数很有用。