2014-01-27 67 views
-6

任何人都可以修复此代码中的错误?重载函数的错误

# include<iostream> 
using namespace std; 

void bubble_sort (int a[], int size); 
float bubble_sort (float b[], int size); 
int read (int a[], int size); 
float read (float b[], int size); 
void display (int a[], int size); 
void display (float b[], int size); 


    int main() 

{ 

    int const size=10; 

    int a[10]; 

    int b[10]; 

    read (a,size); 

    read (b,size); 

    bubble_sort(a,size); 

    bubble_sort(b,size); 

    display(a, size); 

    display(b, size); 

    return 0; 
} 

    int read (int a[], int size) 
     { 
      cout<<"Enter the integer values:"; 
      for (int i=0; i<10;i++) 
       cin>>a[i]; 

     } 

    float read (float b[], int size) 
     { 
      cout<<"Enter the float values :"; 
      for (int i=0; i<10;i++) 
        cin>>b[i]; 
     } 

    void bubble_sort (int a[], int size) 
     { 
      for (int i = 0; i < size; i++) 
      { 
       for (int j = 0; j < size - 1; j++) 
       if (a[j]>a[j + 1]) 
       { 
        swap = a[j]; 
        a[j] = a[j + 1]; 
        a[j + 1] = swap; 
       } 
      } 
     } 

    float bubble_sort (float b[], int size) 
     { 
      for (int i = 0; i < size; i++) 
      { 
       for (int j = 0; j < size - 1; j++) 
       if (b[j]>b[j + 1]) 
       { 
        swap = b[j]; 
        b[j] = b[j + 1]; 
        b[j + 1] = swap; 
       } 
      } 
     } 


    void display (int a[], int size) 
     { 
      for (int i=0;i<size;i++) 
      cout<<a[i]<<" "; 

     } 

    void display (float b[], int size) 
     { 
        cout<<endl; 
      for(int i=0 ;i<size; i++) 
       cout<<b[i]<<" "; 
     } 

编译器显示重载函数没有上下文类型信息。但我需要使用重载函数。我怎么解决这个问题?

In function ‘void bubble_sort(int*, int)’: 
error: overloaded function with no contextual type information 
       swap = a[j]; 
        ^
error: cannot resolve overloaded function ‘swap’ based on conversion to type ‘int’ 
       a[j + 1] = swap; 
+0

尝试函数模板代替 – taocp

+0

_'compiler显示重载函数没有上下文类型信息'_它是怎么回事?错误文本? –

+0

你正在使用'swap'并且你还没有声明它。碰巧有一个'std :: swap'函数模板。 – chris

回答

3

bubble_sort,你正在做swap = a[j];,但是你还没有真正宣布swap变量。看来你可能打算这样做:

float swap; 

你得到你得到,因为有一个std::swap函数的错误,你已经做了using namespace std;。这正是你不应该这样做的原因之一using namespace std;。如果你没有做到这一点,你的错误会更加清晰:

error: ‘swap’ was not declared in this scope 

还请注意,你不能从你的readbubble_sort函数返回任何东西。

1

1.您的数组a []和b []都是整型数组。如果你不返回任何东西,你可以使用int read(int *,int)和float read(int *,int)。

3.编译器说你超载swap没有上下文信息,因为swap是iostream中的一个预定义函数,你甚至没有定义这个变量。