C ++使变量类型取决于用户输入 [英] C++ make a variable type depend on user input
问题描述
我想要一个为测试目的创建数组的函数:
I want a function that creates an array for testing purposes:
- 使用户选择元素类型的想法是数组将包含(int,float,double)。
- 然后,它必须返回所选类型的数组,而 main 必须将其用作参数。我知道这是通过 void指针完成的,但是如果有人可以提供示例,我将感到非常高兴。
- The idea es to make the user select the type of elements the array will contain (int, float, double).
- Then it has to return an array of the selected type and main has to use it as a parameter. I understand this is done using a void pointer, but I would be glad if someone could provide me an example.
所以这是示例代码
**type** vector()
{
int t;
int op;
cout << "Size: \n";
cin >> t;
**type** * v = new **type**[t]
cout << "Select type\n";
cin >> op;
switch(op) {
case 0:
// Create the array with the selected option...
return * v;
case 1:
// Create the array with the selected option...
return * v;
default:
// Other stuff;
}
}
所以问题是我应该使用哪种类型的函数
So the question would be what type of function should I use, and also what type of dynamic variable should I declare as v.
以及正确完成后如何在其他函数上使用它。
And also how to use it later on other functions once correctly done.
谢谢。
推荐答案
简单的答案是您不能 ,因为数据类型需要在编译时特别声明。
The simple answer is that you cannot, because data types need to be specifically declared at compile time.
如果可以使用boost库,
If you can use boost libraries,
boost::variant<int,float,double> vec;
可以满足您的需求。
您无法使用 union
,因为 std :: vector
不是 POD (普通旧数据类型)
You cannot use union
because std::vector
is not a POD (Plain Old Datatype).
编辑:
@Rob指出:
需要将无效指针转换为指向其他对象的指针-编译时
,然后才能使用它们。因此,答案是
仍然不能使用空指针来创建变量数据类型。
Void pointers need to be converted into a pointer to something else - at compile time - before they can be used that way. So the answer is still "cannot" use void pointers to make a variable data type.
这篇关于C ++使变量类型取决于用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!