..。就是我想做的。我有以下代码:
...
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我想我有一个关于如何处理这个任务的基本问题,而不仅仅是一个简单的错误。
那么,哪里出了问题,如何从一开始就修复/纠正它?
发布于 2011-10-27 04:24:28
编辑:如上所述,您的编译器错误来自于在与您试图使用它的作用域不同的作用域中声明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
}发布于 2011-10-27 04:31:27
简短的回答是:你不能这样做。
C++是一种静态类型语言,这意味着您必须在编译时(即编写代码时)决定变量的类型。您不能说“将x声明为get_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.any和shared_ptr使用,它有一些优点。你是否需要它取决于你(但答案是“不”),你可能只需要一个常见的数字类型就可以了。如果将其设置为long double,通常会获得64位整数精度,以及大量的小数位数范围。
发布于 2011-10-27 04:25:17
你的问题是范围问题..如果您在if块中声明了一个变量,那么它将只存在于该块中。当你到达最后的for循环时,Ao已经不存在了。你可以试试这个:
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);
}
} https://stackoverflow.com/questions/7908338
复制相似问题