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

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

问题描述

我有一个singleton:

I have a singleton:

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

当重新安排一些代码时,我最终得到这个语句by error:

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?

推荐答案

这是由于inject-name这意味着如果 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 的构造函数中,而不使用 qualification 。它还隐藏 B 的范围之外 M :: A 。如果你想使用 M :: A ,那么你必须写 M :: A code> :: 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天全站免登陆