调用函数高于其声明 [英] calling functions above their declaration

查看:128
本文介绍了调用函数高于其声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void foo()
{
bar(); //错误:'bar'尚未声明
}

void bar()
{
}

命名空间N
{
void foo()
{
N :: bar(); //错误:'bar'不是'N'的成员
}

void bar()
{
}
}

class C
{
static void foo()
{
C :: bar(); // work just fine
}

static void bar()
{
}
};

这种不一致性处理函数调用超出声明的原因是什么?

解决方案

你可以定义成员函数无论是在类中,还是在类声明之后,或者每一个。



要在这里获得一致性,这里,函数定义inline的类的规则是它仍然必须编译,

$ c> class C {
static void foo()
{
C :: bar(); // work just fine
}

static void bar()
{}
};

编译与

相同

  class C {
static void foo();
static void bar();
};

void C :: foo()
{C :: bar(); }

void C :: bar()
{}

现在没有魔法的可见性,因为这些函数都可以看到类中声明的一切。


void foo()
{
    bar();          // error: ‘bar’ has not been declared
}

void bar()
{
}

namespace N
{
    void foo()
    {
        N::bar();   // error: ‘bar’ is not a member of ‘N’
    }

    void bar()
    {
    }
}

class C
{
    static void foo()
    {
        C::bar();   // works just fine
    }

    static void bar()
    {
    }
};

What is the rationale behind this inconsistency of treating calls to functions above their declaration? How come I can do it inside a class, but not inside a namespace or at global scope?

解决方案

You can define member functions either inside the class, or after the class declaration, or some of each.

To get some consistency here, the rules for a class with functions defined inline is that it still has to be compiled as if the functions were defined after the class.

Your code

class C {
     static void foo()
     {
         C::bar();   // works just fine 
     }

     static void bar()
     {     }
 }; 

compiles the same as

class C {
     static void foo();
     static void bar();
 }; 

 void C::foo()
 {  C::bar();  }

 void C::bar()
 {     }

and now there is no magic in the visibility, because the functions can all see everything declared in the class.

这篇关于调用函数高于其声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆