1

我尝试使用 C++ (Kdevelop platfrom) 中的类来编写一个简单的代码来计算 ave。我的头文件是:

#include <string>
class gradeBank
{
public:
gradeBank(std::string, float [], int n);
void setCourseName(std::string Coursename);
std::string getCourseName();
void gradeProcess();
float Max();
float Min();
double average();
//
private:
std::string Coursename;
int n;  // n= number of students, size of grade-array
float grade[];
};

我与头文件相关的cpp是:

#include <iostream>
#include <stdio.h>
#include "gradeBank.h"
//
gradeBank::gradeBank(std::string name, float gradeArray[], int n)
{
setCourseName(name);
float grade[n];
for (int i = 0; i < n; i++)
    grade[i] = gradeArray[i];
}
//
void gradeBank::setCourseName(std::string name)
{
Coursename = name;
}
//
std::string gradeBank::getCourseName()
{
return Coursename;
}
//
void gradeBank::gradeProcess()
{
std::cout << "class average is: " << average() << std::endl;
std::cout << "Maximum grade is: " << Max() << std::endl;
std::cout << "minimum grade is: " << Min() << std::endl;
}
//
float gradeBank::Max()
{
float max = 0.0;
for (int i = 0; i < n; i++)
    max = max > grade[i] ? max : grade[i];
return max;
}
//
float gradeBank::Min()
{
float min = 0.0;
for (int i = 0; i < n; i++)
    min = min > grade[i] ? min : grade[i];
return min;
}
//
double gradeBank::average()
{
double sum = 0.0, ave;
for (int i = 0; i < n; i++)
sum += grade[i];
ave = sum / n;
return ave;
}

程序的主体是:

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include "gradeBank.h"
#include <iostream>
//
int main()
{
std::string name;
int num, i;
float gradeArray[num];
std::cout << "Please enter the name of the course: ";
std::cin >> name;
std::cout << "Please enter number of students: ";
std::cin >> num;
for (i = 0; i < num; i++)
  {  std::cout << "Studnet " << i << " : ";
    std::cin >> gradeArray[i];
    std::cout << std::endl;
  }
gradeBank t1(name, gradeArray[], num);
t1.gradeProcess();
std::cin.get();
  return 0;
}

我收到以下错误:

 In function ‘int main()’:
 ...e/main.cpp:23: error: expected primary-expression before ‘]’ token

谢谢你们的帮助

4

3 回答 3

2

改变这个:

gradeBank t1(name, gradeArray[], num);

对此:

gradeBank t1(name, gradeArray, num);
于 2013-02-21T14:13:50.873 回答
2

在第 23 行,您错误地传递了数组,它应该是

gradeBank t1(name, gradeArray, num);
于 2013-02-21T14:14:10.927 回答
2

传递数组时,您永远不应该添加 [ ]。所以这条线应该是这样的:

gradeBank t1(name, gradeArray, num);

如果要传递某个元素,请仅使用 [ ],例如:gradeArray[5]

于 2013-02-21T14:17:22.907 回答