对象生成问题求解
class sam
{
protected:
~sam() {}
public:
sam() : i(0)
{}
int i;
};
sam s; // error
sam* ps = new sam; // ok
why compiler complain about the first statement?
Thanks in advance
问题点数:20、回复次数:3Top
1 楼T34(我是坦克我怕谁)回复于 2002-04-17 22:11:10 得分 12
I think, in the 1st case, the compiler generate s on the stack for you, and will call destructor for you when the life of s is ended.
suppose you have the following code
void f()
{
sam s;
some action;
}
the compiler will translate it into something like this
void f()
{
allocate s on stack
sam::sam(&s);
some action;
sam::~sam()
}
so it complains for lacking of desctuctor.
in the 2nd case, you new a sam class object on heap, so it is up to you to free it, and no error occurs, but of course delete ps will not be safe.Top
2 楼rovoboy(魂之猎人)回复于 2002-04-17 22:12:46 得分 8
My English Bad.
May Some Language Mistake.
delete ps;
Will Fail Because Of The Same Reason As sam a
sam s;
Compiler Confirms That You Can Do sam() & ~sam()
sam* ps = new sam;
Compiler Only Confirms That You Can Do sam()
delete ps;
Compiler Only Confirms That You Can Do ~sam()
Top
3 楼wlz47(秋水沉舟)回复于 2002-04-17 22:20:44 得分 0
if use
delete ps; // compile error hereTop




