// AirlineTicket.h
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int getNumberOfMiles();
private:
int mNumberOfMiles;
};
我现在想知道这段代码中 ~AirlineTicket();
的含义是什么?我不知道 ~
(波浪线)是什么意思。
// AirlineTicket.h
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int getNumberOfMiles();
private:
int mNumberOfMiles;
};
我现在想知道这段代码中 ~AirlineTicket();
的含义是什么?我不知道 ~
(波浪线)是什么意思。
这是析构函数。
当你销毁对象实例(即到达作用域结尾,或者调用delete
来释放指向该对象的指针)时,它会被调用。
~
的含义是什么?而提问者只在一个上下文中看到过它的使用,我向他展示了另一个上下文,在那里相同的符号具有完全不同的含义! - Nawaz~
符号表示它是一个析构函数,当对象超出范围时,相应的析构函数就会被调用。
什么时候调用析构函数?
举个例子 -
#include <iostream>
class foo
{
public:
void checkDestructorCall() ;
~foo();
};
void foo::checkDestructorCall()
{
foo objOne; // objOne goes out of scope because of being a locally created object upon return of checkDestructorCall
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
}
int main()
{
foo obj; // obj goes of scope upon return of main
obj.checkDestructorCall();
return 0;
}
我的系统上的结果:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
这个例子只是用来说明析构函数何时被调用。但是只有当类管理资源时才会编写析构函数。
什么是类管理资源?
#include <iostream>
class foo
{
int *ptr;
public:
foo() ; // Constructor
~foo() ;
};
foo:: foo()
{
ptr = new int ; // ptr is managing resources.
// This assignment can be modified to take place in initializer lists too.
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
delete ptr ; // Returning back the resources acquired from the free store.
// If this isn't done, program gives memory leaks.
}
int main()
{
foo *obj = new foo;
// obj is pointing to resources acquired from free store. Or the object it is pointing to lies on heap. So, we need to explicitly call delete on the pointer object.
delete obj ; // Calls the ~foo
return 0;
}
我的系统上的结果:
Destructor called 0x9b68008
在您发布的程序中,我认为不需要编写析构函数。希望这有所帮助!
~
引入了一个析构函数。它的使用是因为(a)它是可用的,以及(b)~
是“不”的数学符号之一。
~
也可以表示按位取反。 - user418748