真的该抽出时间看一看C++,BAT笔试中总是有C++,自己总是拿java的思维想C++,还大部分都是错的O(∩_∩)O,主要还是大一的时候不好好学习,连基本的C++素养都没有,So Stupid...
新鲜出炉的阿里C++笔试题( ̄ ̄)"
#include <iostream>
using namespace std;
class A {
public:
A()
{
cout<<"A()"<<endl;
}
~A()
{
cout<<"~A()"<<endl;
}
};
class B: public A {
public:
B()
{
cout<<"B()"<<endl;
}
~B()
{
cout<<"~B()"<<endl;
}
};
int main() {
A* pA = new B();
delete pA;
B* pB = new B();
delete pB;
return 0;
}
运行结果:
A()
B()
~A()
A()
B()
~B()
~A()
- 真他妈奇怪,竟然没有调用~B(),这C++多态到底是干什么的,难道就这样华丽丽的内存泄露啦w(゚Д゚)w
经过查找资料,原来需要在父类的析构函数中加上virtual关键字,so stupidO(∩_∩)O,代码修改如下:
#include <iostream>
using namespace std;
class A {
public:
A()
{
cout<<"A()"<<endl;
}
virtual ~A()
{
cout<<"~A()"<<endl;
}
};
class B: public A {
public:
B()
{
cout<<"B()"<<endl;
}
~B()
{
cout<<"~B()"<<endl;
}
};
int main() {
A* pA = new B();
delete pA;
B* pB = new B();
delete pB;
return 0;
}
再次运行:
A()
B()
~B()
~A()
A()
B()
~B()
~A()
哎呀妈,这C++,还是C++--(JAVA)省心,永远不用洗碗O(∩_∩)O:
class A {
public A() {
System.out.println("A()");
}
}
public class Main extends A{
public Main() {
System.out.println("Main()");
}
public static void main(String[] args) {
A a = new Main();
Main main = new Main();
}
}
运行结果:
A()
Main()
A()
Main()