C++中的向量只能读取最后一个元素

C++中的向量只能读取最后一个元素,c++,C++,我向向量中添加了几个元素,但当我访问它们时,它们都是最后添加的元素。我不明白 这是我的密码: while(true){ cin>>shape; if(shape=='X') break; if(shape=='C'){ cin>>x>>y>>r; Circle c(x,y,r); shapes[sum] = &c; //cout<<shape

我向向量中添加了几个元素,但当我访问它们时,它们都是最后添加的元素。我不明白

这是我的密码:

while(true){
    cin>>shape;
    if(shape=='X') break;
    if(shape=='C'){
        cin>>x>>y>>r;
        Circle c(x,y,r);
        shapes[sum] = &c;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    }else if(shape=='R'){
        cin>>x1>>y1>>x2>>y2;
        Rectangle rec(x1,y1,x2,y2);
        shapes[sum] = &rec;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    } else if(shape=='T'){
        cin>>x1>>y1>>x2>>y2>>x3>>y3;
        Triangle tr(x1,y1,x2,y2,x3,y3);
        shapes[sum] = &tr;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    }
}
for(int j=0; j<sum; j++){
    showArea(shapes[j]);
}

我最后发现,向量中的所有元素都是相同的,它们是最后添加的元素。

向量存储指针。并在其中存储局部变量指针:

} else if(shape=='T'){
    cin>>x1>>y1>>x2>>y2>>x3>>y3;
    Triangle tr(x1,y1,x2,y2,x3,y3); // <= Create local variable, automatic allocation
    shapes[sum] = &tr; // <= store its address
    //cout<<shapes[sum]->getArea()<<endl;
    sum++;
} // <= automatic dealocation of tr, ie tr doesn't exist anymore
  // shapes[sum - 1] stores address of no more existing variable => Undefined behavior
你应该做:

} else if(shape=='T'){
    cin>>x1>>y1>>x2>>y2>>x3>>y3;
    Triangle *tr = new Triangle(x1,y1,x2,y2,x3,y3); // manual allocation
    shapes.push_back(tr);
    //cout<<shapes[sum]->getArea()<<endl;
    sum++;
} 
但当向量中不再需要对象时,必须取消分配delete

sum不是必需的:您必须使用push_back来避免未定义的行为,之后,您可以使用shapes.size来检索向量的大小

事实上,访问向量的元素超出了范围,即当您执行向量[n]时,n等于或大于vector.size是未定义的行为


现代的方法:如果你想得到一个简洁的答案而不是猜测,请使用shared_ptr或unique_ptr。存储局部变量=>UB的指针。此外,除非向量从一开始就设置了大小,否则shapes[sum]可能超出范围。另一个未定义行为的例子。你如何知道你的形状向量应该有多大?也许用户只是继续添加元素。所以最好使用shapes.push_。此外,您正在向`&'添加指针,而不是对象本身的副本。从提供的有限代码和类名来看,非常确定指针存储是有意的,这看起来是一个经典的多态性课程。然而,这个方法显然是错误的。但是这个例子是有效的:include使用namespace std;int main{vector k;int*p=new int[15];对于int j=0;jThanks很多,你帮了我很多。