明确地解析类成员的作用域 [英] Resolving explicitly the scope of a class member

查看:229
本文介绍了明确地解析类成员的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

#include <iostream>

struct foo {
    void fun() const { std::cout << "foo::fun()" << std::endl; }
};

auto main() -> int {
  foo f;
  f.fun();
  f.foo::fun();

  return 0;
}



DEMO




  • 如上例所示, foo :: fun()有两种不同的方式。

    DEMO

    • As shown in the above example, member function foo::fun() is evoked with two different ways.

      f.foo::fun()),成员类 foo :: fun()消歧/解决。

      In the second call (i.e., f.foo::fun()), the scope of member class foo::fun() is explicitly disambiguated/Resolved.

      问题


      1. 两个调用之间的区别是什么(即 f.fun() f.foo::fun ))?

      2. 调用成员函数或可公开访问的成员变量是否有明显消除其范围的优势, / li>
      3. 通过显式地消除其范围,调用成员函数或可公开访问的成员变量是否有任何陷阱?

      1. What's the difference between the two calls (i.e., f.fun() and f.foo::fun())?
      2. Are there any advantages in calling a member function or a publicly accessible member variable by explicitly disambiguating its scope against calling it in the classical way?
      3. Are there any pitfalls in calling a member function or a publicly accessible member variable by explicitly disambiguating its scope?


      推荐答案

      一个区别是如果 fun() virtual function,第二种方式会禁止虚拟分派。

      One difference is that if fun() were a virtual function, calling it the second way would inhibit virtual dispatch.

      struct foo {
          void virtual fun() const { std::cout << "foo::fun()" << std::endl; }
      };
      struct bar : foo {
          void fun() const override { std::cout << "bar::fun()" << std::endl; }
      };
      
      auto main() -> int {
        bar b;
        foo *f = &b;
        f->fun();
        f->foo::fun();
      }
      

      输出:

      bar::fun()
      foo::fun()
      

      现场演示

      同样,如果你是从基类隐藏一个函数,它允许你访问基类版本。

      Similarly if you were instead hiding a function from the base class, it allows you to access the base class version.

      struct foo {
          void fun() const { std::cout << "foo::fun()" << std::endl; }
      };
      struct bar : foo {
          void fun(int) const { std::cout << "bar::fun()" << std::endl; }
      };
      
      auto main() -> int {
        bar b;
        b.fun(10);
        b.foo::fun();
      }
      

      这篇关于明确地解析类成员的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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