- 虚析构主要为了实现类多态之间层层虚构,减少内存泄漏。
- 如果不用虚析构,代码如下:
- #include
using namespace std;
class B
{
public:
B()
{
cout << “B()” << endl;
}
~B()
{
cout << “~B()” << endl;
}
};
class A :public B
{
public:
A()
{
cout << “A()” << endl;
}
~A()
{
cout << “~A()” << endl;
}
};
int main()
{
B a = new A();
delete a;
system(“pause”);
return 0;
}
执行结果如下:
A的析构函数的没有走到,从而导致了A的自己的变量内存泄漏。
加上虚析构
#include
using namespace std;
class B
{
public:
B()
{
cout << “B()” << endl;
}
virtual ~B()
{
cout << “~B()” << endl;
}
};
class A :public B
{
public:
A()
{
cout << “A()” << endl;
}
~A()
{
cout << “~A()” << endl;
}
};
int main()
{
B a = new A();
delete a;
system(“pause”);
return 0;
}
执行结果如下:
这样就会执行A的析构函数。
(2)找出数组中唯一重复的元素。
intarr[101],存满了1-100,其中有一个数字是重复的的。请找出来。
(1)我们可以定义一个map。找到重复的直接返回,但是map占用空间。
(2)我们可以求出数组的和,减去1-100的和,就是重复的数字。
(3)我们可以用可以用数组的下标和元素之间的关系。取一个位置的数组值,index=intarr[length-1]-1(其他位置元素容易出问题),我们把intarr[index]的值(-1)。然后index=intarr[index](-1)-1;直到找到intarr[index]为负值,返回index+1即可。代码如下:
#include
using namespace std;
int getUnique(int intarr[], int length)
{
int index = intarr[length - 1] - 1;
while (true)
{
if (intarr[index] < 0)
{
break;
}
intarr[index] *= -1;
index = intarr[index] * (-1) - 1;
}
return index + 1;
}
int main()
{
int intarr[10] = { 1,2,5,9,6,3,7,4,8,6 };
cout << getUnique(intarr, 10) << endl;
system(“pause”);
return 0;
}
第三种方法也有很多种的推广,需要多多使用啊。
C++虚析构和(2)找出数组中唯一的重复元素
最新推荐文章于 2021-03-08 21:14:45 发布