【发布时间】:2014-05-07 11:13:14
【问题描述】:
对不起,我以为我现在已经理解堆栈和堆了,但显然我错了。我声明了堆上的每个对象,但是当第一个方法完成时,我可以通过 std::cout 看到时间为零,即:
startTPtr: 00:00:00
当时间在函数中打印时它可以,但是在函数结束后它会以某种方式被破坏。
我在这里错过了什么重要的东西吗?我应该从函数中返回指针吗?
提前致谢!!!
int main() {
Clock *_clockPtr = new Clock();
MyTime *_startTPtr = new MyTime();
MyTime *_endTPtr = new MyTime();
char *ch = new char[100];
start_app(_startTPtr, _endTPtr, _clockPtr, ch);
cout << "startTPtr: " << *_startTPtr << endl;
return 0;
}
void start_app(MyTime *_startTPtr, MyTime *_endTPtr, Clock *clock, char *ch) {
cout << "Press ENTER to start and finish!";
int newLine = 0;
for (std::string line; std::getline(std::cin, line); ) {
if (newLine == 0) {
std::cout << "... ";
MyTime* myTime1 = new MyTime(clock->give_me_the_time());
_startTPtr = myTime1;
cin >> ch;
} else {
MyTime* myTime2 = new MyTime(clock->give_me_the_time());
_endTPtr = myTime2;
break;
}
cout << "startTPtr: " << *_startTPtr << endl;
newLine++;
}
}
【问题讨论】:
标签: c++ pointers heap-memory stack-memory