看看这段C++代码, 为什么a b 对象销毁的代码不执行?
#include<iostream>usingnamespacestd;classB{public:staticB*pB;staticB*GetB(){returnpB;...
#include <iostream>
using namespace std;
class B
{
public:
static B* pB;
static B* GetB()
{
return pB;
}
B()
{
pB = this;
cout <<"B created"<<endl;
}
~B()
{
cout <<"B destroyed"<<endl;
}
};
B* B::pB = NULL;
class A
{
public:
A()
{
cout <<"A created"<<endl;
new B;
}
~A()
{
delete B::GetB();
cout <<"A destroyed"<<endl;
}
};
A a;
void main()
{
} 展开
using namespace std;
class B
{
public:
static B* pB;
static B* GetB()
{
return pB;
}
B()
{
pB = this;
cout <<"B created"<<endl;
}
~B()
{
cout <<"B destroyed"<<endl;
}
};
B* B::pB = NULL;
class A
{
public:
A()
{
cout <<"A created"<<endl;
new B;
}
~A()
{
delete B::GetB();
cout <<"A destroyed"<<endl;
}
};
A a;
void main()
{
} 展开
2个回答
展开全部
A/B销毁的代码其实已经执行,但是cout没有成功执行,可能是因为iostream对象先于A、B释放了,改用printf可以看到,A、B的销毁代码是执行了的。如下代码:
#include <iostream>
using namespace std;
class B
{
public:
static B* pB;
static B* GetB()
{
return pB;
}
B()
{
pB = this;
cout <<"B created"<<endl;
}
~B()
{
printf("B destroyed\n");
}
};
B* B::pB = NULL;
class A
{
public:
A()
{
cout <<"A created"<<endl;
new B;
}
~A()
{
delete B::GetB();
printf("A destroyed\n");
}
};
A a;
void main()
{
}
#include <iostream>
using namespace std;
class B
{
public:
static B* pB;
static B* GetB()
{
return pB;
}
B()
{
pB = this;
cout <<"B created"<<endl;
}
~B()
{
printf("B destroyed\n");
}
};
B* B::pB = NULL;
class A
{
public:
A()
{
cout <<"A created"<<endl;
new B;
}
~A()
{
delete B::GetB();
printf("A destroyed\n");
}
};
A a;
void main()
{
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询