注册 登录
编程论坛 C++教室

[求助]为什么会是这样的结果?

ioriliao 发布于 2007-06-15 11:32, 569 次点击

#include <cstdlib>
#include <iostream>

using namespace std;

class point
{
public:
int x;
int y;

point(int x,int y);
~point();
void print();
};

point::point(int x,int y)
{
this->x=x;
this->y=y;
}

point::~point()
{
cout<<"Unload me"<<endl;
}

void point::print()
{
cout<<"x= "<<this->x<<endl;
cout<<"Y= "<<this->y<<endl;
}

int main(int argc, char *argv[])
{
point* xy=new point(10,10);
xy->print();
delete xy;
xy->print();
system("PAUSE");
return EXIT_SUCCESS;
}
/*
运行结果:
x= 10
y= 10
Unload me
x=0
y=10

为什么结果会是这样的呢,我预期的结果是:

x= 10
y= 10
Unload me
x=0
y=0

谢谢!
*/

7 回复
#2
Arcticanimal2007-06-15 12:25
为什么预期是
x= 10
y= 10
Unload me
x=0
y=0

结果并不能预期~
#3
ioriliao2007-06-15 12:31
#4
aipb20072007-06-15 12:49
x= 10
Y= 10
Unload me
x= -572662307
Y= -572662307


这是用非dev-cpp运行的结果!
明白了吧!呵呵~
#5
HJin2007-06-15 13:49

point::point(int x,int y)
{
this->x=x;
this->y=y;
}

// the above is not recommended. Use the initializer is the correct way
point::point(int x_,int y_) : x(x_), y(y_)
{
}


.....

delete xy;
xy->print();
// this should be undefined behavior, after your obj is destroyed.

#6
ioriliao2007-06-15 14:30
#7
ioriliao2007-06-15 14:43
以下是引用aipb2007在2007-6-15 12:49:47的发言:
x= 10
Y= 10
Unload me
x= -572662307
Y= -572662307


这是用非dev-cpp运行的结果!
明白了吧!呵呵~

版主高明,知道我用的是dev-c,我真是笨死了,我有四五个编译器,乍地就不用它们试试看.
谢谢!

#8
ioriliao2007-06-15 14:53
C:\Documents and Settings\Administrator\My Documents\main.cpp In constructor `point::point(int, int)':
41 C:\Documents and Settings\Administrator\My Documents\main.cpp `x_' undeclared (first use this function)
(Each undeclared identifier is reported only once for each function it appears in.)
41 C:\Documents and Settings\Administrator\My Documents\main.cpp `y_' undeclared (first use this function)
C:\Documents and Settings\Administrator\My Documents\Makefile.win [Build Error] exe: *** [Objects/MingW/main.o] Error 1

HJin兄,你的代码我copy下载编译会出错,怎么回事?
错误指向这句:(上面的是出错提示)
point::point(int x_,int y_) : x(x_), y(y_)
{
}
1