我无法想出一个很好的方法来表达这一点,但我不知道为什么,即使它会编译,它也会在执行时崩溃。 我试图调用类函数,nextTrain()到我的类指针apt,然后它在我重新分配指针之前工作,但是,在运行行之后
apt = apt->nextTrain()
不能再调用类似的类函数了。
完整代码:
#include <iostream>
#include <string>
using namespace std;
class train {
public:
string cars[100];
int index;
int total;
train(string n) { cars[0] = n; index=0; total=0;}
train(string c[100], int ix, int t) {
for (int i = 0; i < 100; i++) {
cars[i] = c[i];
}
index = ix; total = t;
}
train* nextTrain() {
train t(cars, index, total);
train* ret = &t;
ret->atoix(1);
return ret;
}
train* prevTrain() {
train t(cars, index, total);
train* ret = &t;
ret->atoix(-1);
return ret;
}
void atoix(int val) {
index += val;
}
void add(string name) {
cars[total+1] = name;
total++;
}
string getName() {
return cars[index];
}
};
int main()
{
train a("Engine");
train* apt = &a;
apt->add("Train2");
apt->add("Train3");
cout << apt->nextTrain()->getName() << endl;
apt = apt->nextTrain();
cout << apt->getName() << endl;
cout << apt->nextTrain()->getName() << endl;
cout << apt->prevTrain()->getName() << endl;
cout << apt->getName() << endl;
}
答案 0 :(得分:3)
如果我们仔细查看nextTrain
函数中的代码:
train t(cars, index, total);
train* ret = &t;
...
return ret;
变量t
是函数内的 local 变量。当函数返回t
时,将超出范围,对象将被销毁。但是,您返回一个指向此局部变量的指针。一旦变量超出范围,它就不再存在,使用这个(现在无效的)指针将导致未定义的行为。
解决此问题的方法取决于您将如何使用它。我的建议是不从函数返回指针,但返回一个对象实例。即。
train nextTrain() {
train t(cars, index, total);
t.atoix(1);
return t;
}
甚至
train nextTrain() {
return train(cars, index+1, total);
}