c++ - 抽象基类中私有(private)虚函数的可见性

标签 c++ inheritance language-lawyer virtual-functions

考虑以下代码:

class A {
public:
  virtual void f() const = 0;
  void callf() const { f(); }
};

class B : public A {
  virtual void f() const { }
};

int main()
{
  B x;
  x.callf();

  return 0;
}

B 派生自抽象基类 A,但将实现的方法 f() “隐藏”为私有(private)成员。 尽管如此,继承的成员 callf() 仍然能够调用在基类中公开的 f()。 代码在 g++ 10.1.0 和 clang++ 11.1.0 上编译时没有警告。

这是合法的代码吗,即继承的 callf() 是否正确地看到私有(private)成员 f()

或者,派生类 B 是否可以实现基类的纯虚方法,这样它们只能被 B 调用(并且 friend )?

最佳答案

Is this a legal code, i.e., does the inherited callf() correctly see the private member f()?

是的,这是合法的代码。从编译器的角度来看,callf 函数正在引用它自己的 类的f 函数;这是一个虚函数这一事实不会影响作用域(或可访问性)——只会影响实现,它将以调用 v 表条目的形式出现。当通过派生类调用时,该 v 表条目将在运行时得到正确解释。

关于c++ - 抽象基类中私有(private)虚函数的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68438148/

相关文章:

c# - 是否可以将 .net Stream 包装为 STL std::ostream*?

c++ - 在没有组合的情况下对嵌套的 boost::bind 执行参数替换

c++ - std::thread 在 DLLMain 中导致死锁

Java 初学者 : does casting result in lower performance by any mean?

c++ - 编译时模板限制 C++

C++ 后缀表达式未定义与未指定行为

c++ - C++中获取特定函数名的字符串

java - 更改父类(super class)从子类实现的接口(interface)的值会影响所有实例

c - 线程为 "suspended"对 POSIX 意味着什么?

c++ - 如何从模板创建带有 C 链接的函数?