根据运行时创建类型的数组

Creating an array of a type depending on runtime

本文关键字:数组 类型 创建 运行时      更新时间:2023-10-16

。。。是我想做的。我有以下代码:

... 
    int len = 0; 
    char c; 
    bool fp = false;
    while (infile.good()) {
            c = infile.get();
            if (c == 'n') ++len;
            else if (c == '.') fp = true;
    }  
    if (fp == true){
            float Ai[N];
            float *Ao = new float [len];
    } else {
            int Ai[N];
            int *Ao = new int [len];
    }  
    for (int i=0; i<L; ++i){
            for (int j=0; j<N; ++j) infile >> Ai[j];
            Ao[i] = findmax(Ai);
    }
...

如果在文件中检测到小数点,或者如果没有检测到整数,它应该使数组包含双精度。

我还没有检查第一个循环,因为我没有编译它:

warning: unused variable ‘Ai’                                                         
warning: unused variable ‘Ao’
warning: unused variable ‘Ai’
warning: unused variable ‘Ao’
error: ‘Ai’ was not declared in this scope
error: ‘Ao’ was not declared in this scope

我想我在如何处理这项任务方面有一个根本问题,而不仅仅是一个简单的错误。

那么,什么是错误的,如何从一开始就纠正/纠正?

编辑:如上所述,您的编译器错误来自于Ao和Ai在不同于您尝试使用它的范围内声明


这就是模板真正派上用场的地方。

template<typename T>
T *findMaxes(inFile)
{
    T Ai[N];
    T *Ao = new T[len];
    for (int i = 0; i < L; ++i)
    {
        for (int j = 0; j < N; ++j)
            infile >> Ai[j];
        Ao[i] = findmax(Ai);
    }
    return Ao;
}


int len = 0; 
char c; 
bool fp = false;
while (infile.good()) {
        c = infile.get();
        if (c == 'n') ++len;
        else if (c == '.') fp = true;
}  
if (fp)
{
    float *Ao = findMaxes<float>(inFile);
    // Do stuff with the floating point array
}
else
{
    int *Ao = findMaxes<int>(inFile);
    // Do stuff with the int array
}

简短的回答是:你不能这样做。

C++是一种静态类型语言,这意味着您必须在编译时(即编写代码时(决定变量的类型。您不能说"声明xget_type_from_user()类型"之类的话。

使用基于继承的多态性,您可以设置一些设置,通过基类引用处理所有内容,但实际的实例化类型是在运行时确定的。我想,这对你的设置来说肯定是小题大做了,但这是C++中处理运行时依赖细节的标准方式。然而,这对基元类型不起作用,基元类型是类类型的而不是

这里有一个天真的、类型擦除过度的例子:

class NumberImpl;
class Number
{
  NumberImpl * pNum;
public:
  explicit Number(int n) : pNum(new NumberInteger(n)) { }
  explicit Number(double d) : pNum(new NumberDouble(d)) { }
  // ..
};
class NumberImpl { /* ... common implementation interface here ... */ }
class NumberInteger : public NumberImpl
{
  int n;
public:
  NumberInteger(int m) : n(m) { }
  // ...
};
// and so forth

这种类型的擦除boost.anyshared_ptr使用,并且它具有一些优点。你是否需要它取决于你(但答案是"不"(,你可能只需要一种常见的数字类型就可以了。如果你把它设为long double,你通常会得到64位的积分精度,加上吨的刻度范围。

您的问题在于范围。。如果在if块中声明一个变量,它将只存在于该块中。当你进入最后一圈时,奥已经不存在了。你可以试试这个:

if (fp == true)
{
    float Ai[N];
    float *Ao = new float [len];
    for (int i=0; i<L; ++i)
    {
        for (int j=0; j<N; ++j) infile >> Ai[j];
        Ao[i] = findmax(Ai);
    }
}
else 
{
    int Ai[N];
    int *Ao = new int [len];
    for (int i=0; i<L; ++i)
    {
        for (int j=0; j<N; ++j) infile >> Ai[j];
        Ao[i] = findmax(Ai);
    }
}  

您对这里的基本问题是正确的。You Ai变量在结束时超出了范围"}"。所以你以后不能再使用它们了。这也解释了警告,因为在这些变量消失之前,你永远不会使用它们。

C++是静态类型的,所以不能在运行时只更改变量的类型。

您可以查看并集,将float或int放入变量中。一种更接近C++的方法可能涉及继承。但是,如果只有这两种情况,您也可以复制代码(duck(。