如何解决push_back是否会更改存储在其向量中的类型的结构?
我有以下2个课程:
npx create-react-app my-app
和
class Core
{
public:
Core() : mid(0),fin(0) {}
Core(std::istream &in)
{
read(in);
}
virtual ~Core() {}
Str name() const
{
return n;
}
virtual double grade() const
{
return vec_grade(mid,fin,hws);
}
virtual std::istream &read(std::istream &in);
protected:
std::istream &read_common(std::istream &in);
double mid,fin;
Vec<double> hws;
virtual Core *clone() const
{
return new Core(*this);
}
private:
friend class Student2;
Str n;
};
std::istream &Core::read_common(std::istream &in)
{
in >> n >> mid >> fin;
return in;
}
std::istream &Core::read(std::istream &in)
{
read_common(in);
read_vec(in,hws);
return in;
}
现在的问题是这样:
class Student2
{
Core *cp;
public:
Student2() : cp(0) {}
Student2(std::istream &in) : cp(0)
{
read(in);
}
Student2(const Student2 &s) : cp(0)
{
if (s.cp)
s.cp->clone();
}
Student2 &operator=(const Student2 &s);
~Student2()
{
delete cp;
}
std::istream &read(std::istream &in);
Str name() const
{
if (cp)
return cp->name();
else
throw std::runtime_error("uninitialized Student");
}
double grade() const
{
if (cp)
return cp->grade();
else
throw std::runtime_error("uninitialized Student");
}
static bool compare(const Student2 &x,const Student2 &y)
{
return x.name() < y.name();
}
Core *getPointer() const
{
return cp;
}
};
std::istream &Student2::read(std::istream &in)
{
delete cp;
char ch;
in >> ch;
if (ch == 'U')
{
cp = new Core(in);
}
else
{
cp = new Grad(in);
}
return in;
}
输出:
int main()
{
vector<Student2> v;
Student2 s(cin);
v.push_back(s);
printf("%p\n%p\n",s.getPointer(),v[0].getPointer());
}
在这里我被读入对象0x562fa03b9280
(nil)
,该对象将具有其地址。但是一旦我通过Student2
将其添加到向量中,相同的 objetc就会以某种方式丢失(将得到空指针)其地址。我不知道push_back
是如何修改其值的,但是不应该这样做(因为否则它将获得其值)。 push_back
的值是什么?
解决方法
它使用您编写的复制构造函数。这个:
Student2(const Student2 &s) : cp(0)
{
if (s.cp)
s.cp->clone();
}
将cp
设置为null(0)。这就是副本的cp
为空的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。