【问题标题】:Warning to use encapsulated functions [closed]警告使用封装函数[关闭]
【发布时间】:2016-07-24 01:20:42
【问题描述】:

我无法使用私有对象对数组进行排序,并且它们被封装(具有 getter 和 setter)。我正在使用自己的冒泡排序函数。

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;              
               }
          }
     }

问题在于 Eclipse IDE 向我发送警告,在我的类声明中使用 getter 和 setter。

为什么使用 getter 和 setter 更好?

附言 抱歉我的问题很糟糕(这是我的第一个问题):)

【问题讨论】:

  • 我认为你并不完全理解函数签名的意义。它指定如何调用函数。这与您之前犯的错误有关:“如何在函数中定义数组” - 不,您定义了数组 outside bubbleSort。最好没有new[ ]

标签: c++ arrays oop


【解决方案1】:
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.

【讨论】:

  • 显示代码我们需要MVCE
  • 即使是新手,您也可以清楚地提出问题,并发布足够多的代码以清楚地说明您遇到的问题。
  • 现在好点了吗?
【解决方案2】:

在将其作为参数发送给函数之前,您需要创建所述数组。或者,您可以在函数内创建它,但我认为这不是您想要的。

Student* students = new Student[5];

你应该在调用你的函数之前把它写在某个地方。然后,您的函数签名将不得不转向以下内容:

void bubbleSort(Student* student)

一个合乎逻辑的做法是在这里使用std::vector,但它比您要使用的方法要好得多。见:http://en.cppreference.com/w/cpp/container/vector

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2018-08-26
    • 2015-05-19
    • 2011-04-05
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多