[英]c++ returning custom class from function
自从我使用C ++以来已经有一段时间了,我试图编写一个短函数来处理格式为“ {{0.00,0.00);(1.00,0.00);(0.00,1.00); (1.00,1.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;
}
}
}
我的字符串算术全部正确返回,并且代码编译并运行,但是即使正确的值向下传递到addData方法,我的TwoDMap类仍在主方法循环中返回全0。
经过大量的故障排除和调试后,我认为问题在于如何传递自定义类TwoDMap。 但是,在尝试了几种变化(传递二维数组,传递一维数组,传递指向数组的指针,传递带有内部一维数组的TwoDMap以及传递到TwoDMap上的这种变化)之后,我对于以这种方式执行操作的正确方法不知所措。
如何从以这种方式编写的函数中传递出类似列表的对象?
谢谢!
亚历克斯
通过参考传递地图:
void processStringVertex(TwoDMap & return_vector, int vert_index, int dimension,
/* ^^^ */ std::string input_vertex)
如果像现在一样按值传递它,则永远不会修改原始映射(即processStringVector
的局部变量array2D
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.