如何用C ++改进这个类?

时间:2015-09-21 16:54:52

标签: c++ class

我写了这个类(下面)但我的编译器显示错误。有人知道这里有什么问题吗?感谢您的帮助,对不起我的英语,我刚刚开始学习。

我写这个类来转换成绩:用百分比写字母,反之亦然。但有些事情是错的,你能解决这个问题吗?

关于错误:

10:89: error: 'constexpr' needed for in-class initialization of static data member 'char Grade::grade_map [15]' of non-integral type [-fpermissive] 
11:55: error: ISO C++ forbids in-class initialization of non-const static member 'Grade::letter' 
11:55: error: scalar object 'Grade::letter' requires one element in initializer 
14:12: error: expected ':' before 'Grade' In constructor 'Grade::Grade()': 
17:30: error: array must be initialized with a brace-enclosed initializer 
16:19: warning: unused variable 'grade_map' [-Wunused-variable] 
17:19: warning: unused variable 'letter' [-Wunused-variable] 
18:11: warning: unused variable 'percent' [-Wunused-variable] In function 'int main()': 
48:125: error: no matching function for call to 'Grade::printGrade(Grade&)' 
48:125: note: candidate is: 
33:6: note: void Grade::printGrade(Grade*) 
33:6: note: no known conversion for argument 1 from 'Grade' to 'Grade*' 
45:8: warning: unused variable 'geade_map' [-Wunused-variable] 
46:8: warning: unused variable 'letter' [-Wunused-variable] 

这是我在C ++中的课程:

#include <iostream>
#include <cstdio>
using namespace std;

    class Grade // my class

    {
      public:

    static char grade_map [15]; 
    static char letter;
    int  percent;

     public Grade ()
          {                         
     static char grade_map [15];
      static char letter[20]='A';
      int percent = 1;
        }

        void setGradeByPercent(Grade * grade, int percent) 
         {
           grade->percent = percent;
          grade->letter = grade_map [percent / 10];
         }

        void setGradeByLetter(Grade * grade, char letter)
       {
         grade->letter = letter;
         grade->percent = 100 - (letter - 'A') * 10 - 5;
         }

        void printGrade(Grade * grade)
        {
           printf("Grade: %d: %c\n", grade->percent, grade->letter);
        }  

         };

           **int main ()**

           {
              Grade g;
              int percent;
             char grade_map[15];
              char letter[20];

          cout << "Enter two grades separated by a space. Use                            percentage       for         first and       letter   for the second: " << g.printGrade (g) << endl;

       scanf("%d", &percent);
       scanf("\n");    

         g.setGradeByPercent(&g, percent);
         g.printGrade(&g);
           g.setGradeByLetter(&g, getchar());
          g.printGrade(&g);

                     return 0;
              }

1 个答案:

答案 0 :(得分:0)

你的第一个问题是构造函数,你需要在public之后首先需要冒号,然后使用一种完全错误的方法来初始化类成员。

如果你简化这个,至少它会编译:

public:
   Grade()
   {                         
       letter='A';
       percent = 1;
   }

第二个问题是你有g.printGrade (g)作为cout的参数。但是,该函数返回void,因此无法打印。