对不起,但我想现在我已经理解了堆栈和堆,但显然我错了。我宣布堆中的每个对象,但都是一样的,当第一梅托德做我可以通过的std ::法院的时间是ZERO看,那就是:尽管在堆上分配了值,但数值被破坏了
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++;
}
}
[按引用传递动态无功的指针(HTTP的可能重复: //stackoverflow.com/questions/18722208/passing-pointer-of-dynamic-var-by-reference)或http://stackoverflow.com/questions/23250284/scope-of-heap-memory – hmjd