// AirlineTicket.h
#include <string>
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int calculatePriceInDollars();
std::string getPassengerName();
void setPassengerName(std::string inName);
int getNumberOfMiles();
void setNumberOfMiles(int inMiles);
bool getHasEliteSuperRewardsStatus();
void setHasEliteSuperRewardsStatus(bool inStatus);
private:
std::string mPassengerName;
int mNumberOfMiles;
bool fHasEliteSuperRewardsStatus;
};
Run Code Online (Sandbox Code Playgroud)
我现在想要~AirlineTicket();这个代码的含义是 什么?我不知道"〜"(代字号)的含义.
Naw*_*waz 15
在您使用它的上下文中,它定义了一个析构函数.
在其他上下文中,如下所示,它也称为按位否定(补码):
int a = ~100;
int b = ~a;
Run Code Online (Sandbox Code Playgroud)
输出:( ideone)
-101
100
Run Code Online (Sandbox Code Playgroud)
~ 表明它是一个析构函数,并且当对象超出范围时,就会调用相应的析构函数。
何时调用析构函数?
举个例子——
#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;
}
Run Code Online (Sandbox Code Playgroud)
在我的系统上的结果:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
Run Code Online (Sandbox Code Playgroud)
此示例仅用于指示何时调用析构函数。但是析构函数只有在类管理资源时才会写入。
班级什么时候管理资源?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在我的系统上的结果:
Destructor called 0x9b68008
Run Code Online (Sandbox Code Playgroud)
而在程序中,你贴出我认为不需要写析构函数。希望能帮助到你 !
| 归档时间: |
|
| 查看次数: |
59857 次 |
| 最近记录: |