在c ++中,我有一个包含3d定义类型数组的类。我需要定义几个具有int值的属性,并能够设置和获取3d数组的属性。

    //header;
    class Voxel
    {
      private:
        vector< vector < vector < myPoints* > > > Vox; // 3D array
      public:
        //...
     };

     //Here is the constructor and methods of the class:
     Voxel::Voxel(myType var1; double var2)
     {
     // this is constructor

     }


例如,我需要像这样定义具有int值的“属性”:

Attributes:
LabelTag; // Vox tag e.g. an int tag=2
NumberofPoints; // Vox nr of containing points e.g. int nr=5


Vox.setAttribute(LabelTag tag, Value 2);
Vox.setAttribute(NumberofPoints nr, Value 5);

int tag        = Vox.getAttribute(LabelTag);
int nrofpoints = Vox.getAttribute(NumberofPoints);


我应该如何将属性定义为struct或typedef或其他内容,然后如何将值设置为3D数组成员,例如Vox,
我想为Vox本身设置属性,而不是内部的点吗?可能吗?
他们应该定义为私人还是公共?

最佳答案

在第二段代码下面编辑了答案。

好的,首先,如@StoryTeller所评论,您的向量正在存储指针;因此您将需要使用->语法来访问它们所指向的对象。

因此,您可能应该设置myPoints类,因为这种结构是不常见的(c ++中的结构与该类是相同的,除了对它们的属性和函数的默认访问修饰符是公共的)。我想象这堂课看起来像

class myPoints // you should probably split this into a header and cpp
{
    int tag;
    int noOfPoints;

    myPoints() : tag(0), noOfPoints(0) // construct with whatever values, you can pass your own
    {}

    void setNoOfPoints(noOfPoints)
    {
        this->noOfPoints = noOfPoints;
    }

    void setTag(tag)
    {
        this->tag = tag;
    }

    int getNoOfPoints(){ return noOfPoints; }
    int getTag(){ return tag; }
};


假设您已经使用一些* myPoints文字初始化了vox,则可以按如下所示简单地访问和使用myPoints对象

int tag = Vox.at(i).at(j).at(k)->getTag();
int noOfPoints = Vox.at(i).at(j).at(k)->getNoOfPoints();

Vox.at(i).at(j).at(k)->setNoOfPoints(6);
Vox.at(i).at(j).at(k)->setTag(6);


与@Aconcagua的答案一样,保留上面的答案,将来可能会有用。

无论如何,考虑到您已经按照@StoryTeller所说的编写了代码,我想我会更好地理解您想做的事情,您可以只使用Voxel类为每个向量保存tag和noOfPoints属性。 Voxel类的外观类似于(原谅我懒于不提供标题)

class Voxel
{
private:
    vector< vector < vector < myPoints* > > > Vox;

    int tag;
    int noOfPoints;
public:
    Voxel() : tag(0), noOfPoints(0) // construct with whatever values, you can pass your own
    {}

    vector< vector < vector < myPoints* > > >& getVox(){ return Vox; } //Ignore my shitty naming scheme, you can use this to set or get elements

    void setNoOfPoints(noOfPoints)
    {
        this->noOfPoints = noOfPoints;
    }

    void setTag(tag)
    {
        this->tag = tag;
    }

    int getNoOfPoints(){ return noOfPoints; }
    int getTag(){ return tag; }
};


然后访问您的向量并设置标签和noOfPoints,只需创建一个Voxel实例,它应该看起来像这样

//A new vector of voxels

vector<Voxel> voxels;

voxels.push_back(Voxel); // this only needs to be a 1d array, you can construct each voxel however you like and add as many as you like

//settting the tag for the first element

voxels[0].setTag(0);

//getting the tag for the first element

int tag = voxels[0].getTag();

// manipulating the contained vector

voxels[0].getVox().at(i).at(j).at(k) = //whatever you are storing in your vector

10-06 13:15
查看更多