无法将一个类对象深层复制到另一个;
我有一个几何类对象
class Geometry
{
public:
std::string stdstrType;
bool bValid;
public:
Geometry()
{
stdstrType = "NO_TYPE";
bValid = false;
}
Geometry( std::string strType , bool bValue )
{
stdstrType = strType;
bValid = bValue;
}
Geometry(const Geometry &g)
{
stdstrType = g.stdstrType;
bValid = g.bValid;
}
~Geometry()
{
qDebug() << "Geometry destructor called";
}
virtual void draw();
bool isValid();
void setValidState(bool bState);
virtual void Init();
std::string GetName();
};
我有一个Container类
class Container
{
private:
std::string stdstrContainerName;
std::string stdstrPluginType;
Geometry* Geom;
public:
Container();
Container(std::string, std::string, Geometry* geometry = nullptr);
Container(const Container& obj);
~Container();
std::string GetName();
std::string GetType();
void SetName(std::string stdstrName);
Geometry* GetGeometry();
void SetGeometry(Geometry* Geom);
};
Container::Container(std::string strName, std::string strType, Geometry*
geometry) : Geom(geometry)
{
stdstrContainerName = strName;
stdstrPluginType = strType;
}
Container::Container(const Container& obj) {
stdstrContainerName = obj.stdstrContainerName;
stdstrPluginType = obj.stdstrPluginType;
Geom = new Geometry;
*Geom = *obj.Geom; // This Line gives error
}
因为容器对象具有带有几何指针的数据成员,并且几何对象的范围比容器对象短 所以我想在Container对象内做一个深层复制几何对象。
这是复制构造函数中的行,给我错误
*Geom = *obj.Geom; // This Line gives error
这是我初始化容器对象的方式
Geometry* geom = new Geometry;
Container* cont = new Container("Group", "NONE", geom);
答案 0 :(得分:1)
正如@ rafix07所评论的那样,您应该始终在取消引用指针之前检查指针。
if(obj.Geom != nullptr) // Check
*Geom = *obj.Geom;
还要与复制构造函数一起,考虑为Geometry
类定义赋值运算符,以实现深度复制的目的。
Geometry & Geometry::operator = (const Geometry &g)
{
if(this != &g)
{
stdstrType = g.stdstrType;
bValid = g.bValid;
}
return *this;
}
答案 1 :(得分:-1)
如果T具有用户声明的析构函数或用户声明的副本构造函数,则不建议使用隐式定义的副本分配运算符。
您需要为您的班级定义一个赋值运算符
Geometry& operator = (const Geometry &g)
Container& operator = (const Container& c)