为什么会有3个析构函数被调用解决思路
为什么会有3个析构函数被调用
#include <iostream>
class xBoundary
{
public:
// constructors
xBoundary();
xBoundary(const int index);
~xBoundary();
// accessor
int ErrIndex() const {return myIndex;}
private:
int myIndex;
};
// implementations
// The constructors merely print out a message
// indicating they have bee called, along with
// the value of their myIndex property.
xBoundary::xBoundary():
myIndex(-1)
{
std::cout < < "xBoundary() -> myIndex= " < < myIndex < < "\n ";
}
xBoundary::xBoundary(const int index):
myIndex(index)
{
std::cout < < "xBoundary(const int) -> myIndex= " < < myIndex < < "\n ";
}
xBoundary::~xBoundary()
{
std::cout < < "~xBoundary() -> myIndex= " < < myIndex < < "\n ";
}
int main()
{
const int defaultSize = 10;
const int someOtherNumber = 11;
int myArray[defaultSize];
for (int i = 0; i < defaultSize; i++)
myArray[i] = i;
try
{
for (int i = 0; i < someOtherNumber; i++)
{
if (i > = defaultSize)
throw xBoundary(i);
else
std::cout < < "myArray[ " < < i < < "]:\t " < < myArray[i] < < "\n ";
}
}
catch(xBoundary err)
{
std::cout < < "Failed to retrieve data at index " < < err.ErrIndex() < < ".\n ";
}
return 0;
}
输出
#include <iostream>
class xBoundary
{
public:
// constructors
xBoundary();
xBoundary(const int index);
~xBoundary();
// accessor
int ErrIndex() const {return myIndex;}
private:
int myIndex;
};
// implementations
// The constructors merely print out a message
// indicating they have bee called, along with
// the value of their myIndex property.
xBoundary::xBoundary():
myIndex(-1)
{
std::cout < < "xBoundary() -> myIndex= " < < myIndex < < "\n ";
}
xBoundary::xBoundary(const int index):
myIndex(index)
{
std::cout < < "xBoundary(const int) -> myIndex= " < < myIndex < < "\n ";
}
xBoundary::~xBoundary()
{
std::cout < < "~xBoundary() -> myIndex= " < < myIndex < < "\n ";
}
int main()
{
const int defaultSize = 10;
const int someOtherNumber = 11;
int myArray[defaultSize];
for (int i = 0; i < defaultSize; i++)
myArray[i] = i;
try
{
for (int i = 0; i < someOtherNumber; i++)
{
if (i > = defaultSize)
throw xBoundary(i);
else
std::cout < < "myArray[ " < < i < < "]:\t " < < myArray[i] < < "\n ";
}
}
catch(xBoundary err)
{
std::cout < < "Failed to retrieve data at index " < < err.ErrIndex() < < ".\n ";
}
return 0;
}
输出