通过重复对象名称调用静态方法? [英] Calling a static method by repeating the object name?

查看:55
本文介绍了通过重复对象名称调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例:

struct foo {
  static foo& instance() {
    static foo f;
    return f;
  }
};

重新排列一些代码时,我最终以错误声明:

When re-arranging some code I ended up with this statement "by error":

foo::foo::instance()

但是我的编译器(gcc 4.7)认为这是正确的。实际上,即使 foo :: foo :: foo :: instance()也会编译。为什么?

But this is deemed correct by my compiler (gcc 4.7). In fact, even foo::foo::foo::instance() compiles. Why?

推荐答案

这是由于注入名称—这意味着如果 foo 是一个类名,并且相同的名称 foo也被注入到类范围中,这就是您的代码起作用的原因。它是100%符合标准的。

It is due to "injected-name" — which means if foo is a class-name, and the same name "foo" is also injected into the class-scope which is why your code works. It is 100% Standard-conformant.

下面是一个有趣的示例,显示了此功能的好处:

Here is one interesting example which shows the benefits of this feature:

namespace N
{
   //define a class here
   struct A 
   { 
       void f() { std::cout << "N::A" << std::endl; }
   };
}

namespace M
{
   //define another class with same name!
   struct A 
   { 
       void f() { std::cout << "M::A" << std::endl; }
   };

   struct B : N::A  //NOTE : deriving from N::A
   {
         B()
         {
            A a;
            a.f(); //what should it print?
         }
   };
}

af()打电话吗? a 是什么类型?是 M :: A 还是 N :: A ?答案是 N :: A ,而不是 M :: A

What should a.f() call? What is the type of a? Is it M::A or N::A? The answer is, N::A, not M::A.

  • Online Demo

由于名字的插入, N :: A 可用在 B 的构造函数中而没有限定。它还会隐藏 M :: A ,这仍然不在 B 的范围内。如果要使用 M :: A ,则必须编写 M :: A (或更佳的 :: M :: A )。

It is because of name-injection, N::A is available inside the constructor of B without qualification. It also hides M::A, which remains outside the scope of B. If you want to use M::A, then you've to write M::A (or better ::M::A).

这篇关于通过重复对象名称调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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