【问题标题】:Error: 'anil' was not declared in this scope错误:未在此范围内声明“anil”
【发布时间】:2016-07-10 02:16:10
【问题描述】:

为什么即使在主函数中声明了错误 anil 也没有在范围内声明?

#include <iostream>
using namespace std;
struct student
{
    int rollno,classa;
};
void initial(student *);
void display(student *);
int main()
{   student anil={10,11};
    initial(&anil);
    display(&anil);
    return 0;
}
void initial(student *)
{
    anil->rollno=100;anil->classa=10;}
void display(student *)
{
    cout<<anil->rollno<<anil->classa;
}

【问题讨论】:

  • FWIW,你应该通过引用传递,而不是通过指针传递。这是 C++ 和 C++ 可以使用的引用。

标签: c++ c++11


【解决方案1】:

main 函数的范围没有扩展到initial 函数。对于要在范围内的变量,对该变量的引用必须在定义之后和与变量定义之前最近的左大括号匹配的右大括号之前。您还可以在任何花括号之外声明变量;它们将在声明后的任何地方都可以访问,但也将隐含为static

int a;

someFunc()
{
   int b;
} // This closing curly brace ends the scope of 'b'

int c = a + 1; // ok, a was declared outside any brace

【讨论】:

    【解决方案2】:

    anilmain() 中声明,因此它是本地的,对其他函数不可见(即它的范围仅延伸到main() 主体的末尾)。

    要从其他函数访问它,您需要将它作为参数传递给它们(您已经在这样做)并且在函数的签名中具有此参数的名称。所以,在你的情况下,你需要做这样的事情:

    void initial(student * ps)
    {
        ps->rollno=100;ps->classa=10;
    }
    
    void display(student * ps)
    {
        cout<<ps->rollno<<ps->classa;
    }
    

    现在这些函数将能够访问指向anil 的指针,您正在传递给它们,名称为ps

    【讨论】:

      【解决方案3】:

      一个简单的解决方法就是将指针参数命名为 anil,就像这样

      void initial(student *anil)
      

      【讨论】:

        猜你喜欢
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 2010-10-02
        • 2016-02-18
        相关资源
        最近更新 更多