c++从函数返回自定义类

c++ returning custom class from function

本文关键字:自定义 返回 函数 c++      更新时间:2023-10-16

我使用C++已经有一段时间了,我正试图编写一个短函数,将格式为"{(0.00,0.00);(1.00,0.00),(0.00,1.00);(1.001.00)}"的字符串中的向量处理为自定义类。

然而,我很难成功地从函数的自定义类中的字符串中返回值。

在下面查找相关代码:

class TwoDMap
{
private:
    int dim, num_verts;
    std::vector<float> int_array;
public:
    TwoDMap (int num_vertices, int dimension);
    float getData(int num_vert, int dim);
    void addData(float value);
};
TwoDMap::TwoDMap(int num_vertices, int dimension)
{
    num_verts = num_vertices;
    dim = dimension;
    int_array.reserve(num_vertices * dimension);
}
float TwoDMap::getData(int num_vert, int dimension)
{
    return int_array[(num_vert * dim) + dimension];
}
void TwoDMap::addData(float value)
{
    int_array.push_back(value);
}
void processStringVertex(TwoDMap return_vector, int vert_index, int dimension, std::string input_vertex)
{
    //Process a single portion of the string and call the addData method
    //to add individual floats to the map
}
TwoDMap processStringVector(int dimension, int num_vertices, std::string input_vector)
{
    TwoDMap array2D (num_vertices, dimension);
    //Process the whole string, calling the processStringVertex method
    //and passing in the variable array2D
    return array2D;
}
int main()
{
    std::string v = "{(0.00, 0.00); (1.00, 0.00); (0.00, 1.00); (1.00, 1.00)}";
    int dim = 2;
    int num_verts = 4;
    TwoDMap vect = processStringVector (dim, num_verts, v);
    for( int i = 0; i < num_verts; i = i + 1)
    {
        for( int j = 0; j < dim; j = j + 1)
        {
            std::cout << vect.getData(i, j) << std::endl;
        }
    }
}

我的字符串算术都返回正确,代码编译并运行,但我的TwoDMap类在主方法循环中返回所有0,即使正确的值被传递给addData方法。

经过大量的故障排除和调试,我认为问题在于如何传递自定义类TwoDMap。然而,在尝试了几种变体(传递二维数组、传递一维数组、传递指向数组的指针、传递具有内部一维数组的TwoDMap以及TwoDMap上的这种变体)之后,我不知道以这种方式执行操作的正确方式。

如何从以这种方式编写的函数中传递类似列表的对象?

谢谢!

Alex

通过引用传递地图:

void processStringVertex(TwoDMap & return_vector, int vert_index, int dimension,
/*                              ^^^          */          std::string input_vertex)

如果像现在这样按值传递它,则原始映射(即processStringVector中的局部变量array2D)永远不会被修改。