c++从函数返回自定义类
c++ returning custom class from function
我使用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
)永远不会被修改。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 通过 NIF 从C++返回自定义数据结构
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 如何在C++中返回自定义类中的分段错误?
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 如何从 cpp 中的函数返回自定义类对象?
- 将成员函数的返回类型引用到C++中的自定义类
- 自定义派生的 std::exception 类的 'what' 函数返回神秘的废话
- 从 QAbstractItemModel 返回自定义用户类型
- 将 OpenGL 坐标系统转换为自定义并返回
- 基于范围的 for 循环,用于包含C++中的指针的自定义链表,仅返回对象
- C++ grpc::experimental:interceptor 如何从自定义拦截器返回状态和消息
- 是否可以为类设置自定义返回类型
- 具有自定义返回类型和"false"返回条件的函数?
- C :不同类型的模板功能(方法)的自定义返回值
- 在派生类中定义自定义返回类型的受保护方法
- 自定义返回类型声明
- 带有自定义返回值的seresult
- 具有自定义返回类型的全局命名空间中的友元函数