复制具有C ++中没有默认构造函数的成员的类的构造函数 [英] Copy constructor for class that has member without default constructor in C++

查看:164
本文介绍了复制具有C ++中没有默认构造函数的成员的类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程:

class Geometry{
    std::vector<Subset *> subsets;
    int verticesCount;
    ...
};

我想添加一个副本构造函数,因此可以制作一个深层副本该对象(具有自己的子集仅拥有指针来指向相同的子集)。

I want to add a copy constructor, so I can make a deep copy of that object (with own subsets, NOT only own pointers to same subsets).

我已经尝试过:

 Geometry & Geometry::operator=(const Geometry &other){
      verticesCount = other.verticesCount;
      Subset * subset = 0;
      for(unsigned int i=0; i<other.subsets.size(); i++){
           subset = new Subset();
           subsets.push_back(subset);
      }
      ...
      return *this;
 }

问题是子集没有默认构造函数,因此在 subset = new Subset()时出错。

The problem is Subset has none default constructor, so I get error at subset = new Subset().

我还有更多的成员没有默认构造函数。

I also have more members that don't have default constructors.

如何解决该问题?

我希望不要为所有成员添加默认构造函数子集等)。最佳解决方案是根本不能更改成员类(子集等),但是如果有必要,我可以向其中添加一些内容。

I would prefer NOT to add default constructors for all that members (Subset etc.) The best solution would be NOT to change member classes at all (Subset etc.), but I can add something to them, if it's necessary.

他们没有原因的默认构造函数,例如安全性(我不想让某人创建 Model3D 类而不给出文件名(因此可以创建顶点缓冲区,并且我可以假定所有 Model3D 对象没有关联的空文件名。)

They don't have default constructors for reasons, e.g. security (I don't want to let somebody create a Model3D class without giving filename (so the vertex buffers can be created and I can assume that all Model3D objects has not-empty filename associated).

edit:

由于注释。子集是没有默认构造函数的成员类的示例。

Because of comment. Subset is an example of member class without default constructor.

在这种情况下,这是我自己的课程:

In that case it's my own class:

class Subset{
    ...
    public:
        Subset(bool useLineTopology, int vertexIndexStart, int vertexIndexAmmount = -1);
        ...
};

但是我还有很多其他成员没有默认构造函数,例如DirectX的 ID3D11Buffer * constantBuffer

But I also have many others members without default constructor, like DirectX's ID3D11Buffer * constantBuffer.

推荐答案

如果您的 Subset()类具有副本构造函数,则可以执行以下操作:

If your Subset() class has a copy constructor then you can do as follows:

std::vector<Subset *>::const_iterator it ; // use iterators
for ( it = other.subsets.begin() ; it != other.subsets.end() ; ++it )
    subset.push_back( new Subset( *it )) ; // add a copy of original subset.

如果您的 Subset()没有复制构造函数,则无法复制。

If your Subset() does not have copy constructor then you CANNOT copy.

此外,您还需要记住拥有〜GeometryStructure()子集std :: vector

Also, you need to remember to have ~GeometryStructure() in order to delete all Subset() objects from the subset std::vector

这篇关于复制具有C ++中没有默认构造函数的成员的类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆