【发布时间】:2016-07-09 06:53:32
【问题描述】:
来自 Java 背景,以下代码让我感到困惑。这里的困惑是没有 new 关键字的 C++ 对象创建。我正在创建此对象Student_info info;,然后将其添加到向量中。由于我没有使用 new 关键字创建它,它会在堆栈上分配并在循环退出后被销毁吗?如果是这种情况,最后一个循环如何能够正确地从向量中提取信息?由于添加到向量中的所有对象都已销毁,它不应该抛出异常吗?
struct Student_info {
string name;
vector<double> marks;
};
int main()
{
int num = 2;
vector<Student_info> student_infos;
for (int i = 0; i < 3; i++) {
Student_info info; //will this object be destroyed once this loop exits?
cout << "Enter name:";
cin >> info.name;
double x;
cout << "Enter 2 marks";
for (int j = 0; j < num; j++) {
cin >> x;
info.marks.push_back(x);
}
student_infos.push_back(info);
}
for (int i = 0; i < 3; i++) {
cout << student_infos[i].name;
for (int j = 0; j < num; j++) {
cout << student_infos[i].marks[j];
}
cout << endl;
}
return 0;
}
【问题讨论】:
-
由于您来自Java背景,我真的建议您了解变量和指针之间的区别!还要记住,每当您将某些内容作为参数传递时,它都会被复制。当您改用指针时,您会得到 Java 行为。然后你还必须使用
new关键字。
标签: c++ scope declaration