"sort3"未在此范围内声明

'sort3'was not declared in this scope

本文关键字:范围内 声明 sort3      更新时间:2023-10-16

如何更正代码?我不明白sort3 was not declared in this scope的意思。

#include <iostream>
using namespace std;
int main ( )
{
   cout<<" Enter first value. "<<endl;
   int a;
   cin>> a;
   cout<<"Enter second value. "<<endl;
   int b;
   cin>>b;
   cout<<"Enter third value. "<<endl;
   int c;
   cin>>c;
   sort3(a,b,c);
   cout << a << " " << b << " " << c << endl;
   return 0;
}
void sort3(int& a, int& b, int&c )
{
    int temp;
    if (a < b )
    {
        temp = a;
        a = b;
        b = temp;
    }
    else if (a < c )
    {
        temp = a;
        a = c;
        c = temp;
    }
    else if ( b < c )
    {
        temp = b;
        b = c;
        c = temp;
    }
}

您可以在main之前"声明"sort3函数:

void sort3(int& a, int& b, int&c );
int main ()
{
...

另一种选择是将sort3的定义移到main之前。

在C++中,您至少需要一个函数的声明才能使用它。

您需要将声明放在第一次使用函数之前:

#include <iostream>
using namespace std;
void sort3(int& a, int& b, int&c );    //declaration
int main ( )
{

声明

void sort3(int&, int&, int& );

main起作用之前,它将起作用。

将声明放在函数之前:

void sort3(int& a, int& b, int&c )
int main()

或者试试这个:

#include <iostream>
using namespace std;
void sort3(int& a, int& b, int&c )
{
  int temp;
  if (a < b )
  {
    temp = a;
    a = b;
    b = temp;
  }
  else if (a < c )
  {
    temp = a;
    a = c;
    c = temp;
  }
  else if ( b < c )
  {
    temp = b;
    b = c;
    c = temp;
  }
}
int main ( )
{

 cout<<" Enter first value. "<<endl;
 int a;
 cin>> a;
 cout<<"Enter second value. "<<endl;
 int b;
 cin>>b;
 cout<<"Enter third value. "<<endl;
 int c;
 cin>>c;

 sort3(a,b,c);
 cout << a << " " << b << " " << c << endl;
 return 0;
}

请注意,函数的声明必须在使用之前。

试试这个

#include <iostream>
using namespace std;
void sort3(int& a, int& b, int&c )
{
    int temp;
    if (a < b )
    {
        temp = a;
        a = b;
        b = temp;
    }
    else if (a < c )
    {
        temp = a;
        a = c;
        c = temp;
    }
    else if ( b < c )
    {
        temp = b;
        b = c;
        c = temp;
    }
}
int main ( )
{

   cout<<" Enter first value. "<<endl;
   int a;
   cin>> a;
   cout<<"Enter second value. "<<endl;
   int b;
   cin>>b;
   cout<<"Enter third value. "<<endl;
   int c;
   cin>>c;

  sort3(a,b,c);
   cout << a << " " << b << " " << c << endl;
   return 0;
}

或者,您可以在顶部的"using namespace std;"行之后定义函数

void sort3(int &, int &, int &);

由于编译器从上到下解析文件,因此会出现此错误。因此编译器会遇到您对sort3的调用,但它从未被声明。

为了解决这个问题,您可以使用forward声明,或者将整个sort3-函数移到main()前面。

具有前向声明的解决方案:

#include <iostream>
using namespace std;
void sort3(int& a, int& b, int&c );
int main ( )
{
   ... code ...
}
void sort3(int& a, int& b, int&c )
{
    ... code ...
}

没有正向声明,但sort3移动到main():前面

#include <iostream>
using namespace std;
void sort3(int& a, int& b, int&c )
{
    ... code ...
}
int main ( )
{
   ... code ...
}