【发布时间】:2014-11-30 16:27:55
【问题描述】:
在 push_back() 函数中运行我的代码时出现分段错误, 我的程序如下..
程序:
#include<iostream>
#include <vector>
using namespace std;
class Point
{
private:
int x, y;
int * p;
public:
Point(int x1, int y1) {
x = x1; y = y1;
*p = 1;
}
Point(const Point & p2) {
x = p2.x;
y = p2.y;
*p = 1;
}
};
int main()
{
Point p1(10, 15);
Point p2 = p1;
vector<Point> vec;
for (int i=0; i<10; i++)
{
vec.push_back(p2);
}
}
有人可以给出上述程序中分段错误的原因吗???? 有人能给出上述程序中分段错误的原因吗???
【问题讨论】:
-
p是一个指针,但在取消引用它之前,你没有让它指向一个有效的对象。 -
你能解释一下变量p的用途吗?如果你删除它,崩溃就会消失。你永远不会给 p 一个地址,所以你把 1 写到一个随机的内存位置
-
只是想在复制构造函数中增加该变量,以跟踪创建的副本数..