警告使用封装函数

Warning to use encapsulated functions

本文关键字:函数 封装 警告      更新时间:2023-10-16

我在用私有对象对数组进行排序时遇到了问题,这些对象是封装的(有getter和setter)。我使用自己的bubble排序函数。

void BubbleSort(apvector <int> &num)
{
      int i, j, flag = 1;
      int temp;            
      int numLength = num.length( ); 
      for(i = 1; (i <= numLength) && flag; i++)
     {
          flag = 0;
          for (j=0; j < (numLength -1); j++)
         {
               if (num[j+1] > num[j])      
              { 
                    temp = num[j];            
                    num[j] = num[j+1];
                    num[j+1] = temp;
                    flag = 1;              
               }
          }
     }

问题是eclipseIDE向我发出警告,要在类的声明中使用getter和setter。

为什么使用getter和setter更好?

第S页很抱歉我的问题问得不好(这是我的第一个问题):)

void bubbleSort(Student* student, int size)
{ [...] }

变量student是指向数组的指针
您还必须指定数组的大小

称之为:

Student* myClass=new Student[5];
bubbleSort(myClass, 5); // Pass the array, and the size of the array both.

在将上述数组作为参数发送到函数之前,需要创建该数组。或者,你可以在函数中创建它,但我认为这不是你想要的。

Student* students = new Student[5];

在调用函数之前,您应该在某个地方写下这篇文章。然后,您的函数签名必须转到以下位置:

void bubbleSort(Student* student)

不过,合乎逻辑的做法是在这里使用std::vector,它比您要使用的方法要好得多。请参阅:http://en.cppreference.com/w/cpp/container/vector