繁体   English   中英

使用方法声明未知数量的变量

[英]Using a method to declare an unknown amount of variables

我对 C++ 非常陌生,我正在尝试创建一个数学引擎

我有一个名为 Point 的 class,来自这个 class 的对象需要能够保存未知数量的维度值。 我有一个名为 DAmount 的变量,它是在创建点时决定的。 我想要一种方法来获取 DAmount,并创建连接到点 object 的许多变量。

例如,我声明了一个名为“SixDPoint”的点,然后将其 DAmount 设置为 6。然后我使用名为 CreateDVars 的方法创建了六个连接到 object“SixDPoint”的变量。 然后我可以使用这六个变量作为 XYZ+ 轴。

我不知道该怎么做。 这是一些代码来解释我正在尝试做的事情。 非常感谢


#include <iostream>
using namespace std;

class Point
{
  public:

    int DAmount;

    void CreateDVars(int)
    {
      //Variable declaration Function
    }

};

int main()
{

  Point SixDPoint;  //declaring a Point named SixDPoint

  SixDPoint.DAmount = 6;  // this sets the dimension amount, of SixDPoint, to 6

  SixDPoint.D1 = 1;
  SixDPoint.D2 = 1;
  SixDPoint.D3 = 1;
  SixDPoint.D4 = 1;
  SixDPoint.D5 = 1;
  SixDPoint.D6 = 1;
  //this should assign all six dimensions of SixDPoint, to 1
  cout << SixDPoint.D1 << "/n";
  cout << SixDPoint.D2 << "/n";
  cout << SixDPoint.D3 << "/n";
  cout << SixDPoint.D4 << "/n";
  cout << SixDPoint.D5 << "/n";
  cout << SixDPoint.D6 << "/n";
//this should print out all of the coordinates of SixDPoint
  return 0;
}

我相信你想要这样的东西:

#include <iostream>
#include <vector>
using namespace std;

class Point
{
public:

    int DAmount;

    void CreateDVars(int k)
    {
        dim.resize(k);
    }
    int& operator[](int k)
    {
        if (k >= 0 && k < dim.size())
            return dim[k];
    }
private:
    vector<int> dim;
};

int main()
{

    Point SixDPoint;  //declaring a Point named SixDPoint

    SixDPoint.CreateDVars(6);
    SixDPoint[0] = 1;
    SixDPoint[1] = 1;
    SixDPoint[2] = 1;
    SixDPoint[3] = 1;
    SixDPoint[4] = 1;
    SixDPoint[5] = 1;
    //this should assign all six dimensions of SixDPoint, to 1
    cout << SixDPoint[0] << "/n";
    cout << SixDPoint[1] << "/n";
    cout << SixDPoint[2] << "/n";
    cout << SixDPoint[3] << "/n";
    cout << SixDPoint[4] << "/n";
    cout << SixDPoint[5] << "/n";
    //this should print out all of the coordinates of SixDPoint
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM