虚函数调用和依赖基类的混淆理解

发布于 2024-12-11 03:51:49 字数 556 浏览 0 评论 0原文

我正在阅读电子书模板完整指南和问题,我要问的问题对您来说可能很愚蠢,但是..

9.4.2 依赖基类中有一部分我无法理解。

以下是其中的部分文本: http://tinypaste.com/633f0

// Variation 2: 
template<typename T> 
class DD2 : public Base<T> { 
  public: 
    void f() { Base<T>::basefield = 0; } 
}; 

我需要帮助可视化该行(或问题域)在上面的文本中“必须小心此解决方案,因为如果使用非限定的非依赖名称来形成虚拟函数调用,则限定会抑制虚拟调用机制,并且程序的含义会发生变化。尽管如此,在某些情况下,无法使用第一个变体,而这种替代方案是合适的”

我理解不合格的非依赖名称等,但将它们与虚拟函数调用混合是我所无法理解的。

I am reading from ebook Templates complete guide and question which i'm gonna ask might be stupid to you but..

There is section in that 9.4.2 Dependent Base Classes which i am unable to understand.

Here is the partial text from it: http://tinypaste.com/633f0

// Variation 2: 
template<typename T> 
class DD2 : public Base<T> { 
  public: 
    void f() { Base<T>::basefield = 0; } 
}; 

I need help visualizing the line (or problem domain) in text above "Care must be taken with this solution, because if the unqualified nondependent name is used to form a virtual function call, then the qualification inhibits the virtual call mechanism and the meaning of the program changes. Nonetheless, there are situations when the first variation cannot be used and this alternative is appropriate"

I understand unqualified nondependent name etc but mixing them with virtual function call is what eluding me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

祁梦 2024-12-18 03:51:49

如果限定名称 (basefield) 是虚拟函数,则该限定会禁止虚拟调用。这与您拥有以下内容非常相似:

struct Base {
  virtual void vCall() { }
};

struct Derived : public Base {
  virtual void vCall() { }
};

int main() {
  Derived d;
  Base* inst = &d;
  inst->Base::vCall(); // By qualifying we won't get virtual dispatch;
                       // this calls Base::vCall directly
}

If the qualified name ( basefield ) is a virtual function, then the qualification inhibits the virtual call. It's very much the same as if you have:

struct Base {
  virtual void vCall() { }
};

struct Derived : public Base {
  virtual void vCall() { }
};

int main() {
  Derived d;
  Base* inst = &d;
  inst->Base::vCall(); // By qualifying we won't get virtual dispatch;
                       // this calls Base::vCall directly
}
提笔落墨 2024-12-18 03:51:49

使用限定标识符 class-name::function() 会抑制 function 的虚拟性,因此您应该使用 this->function()代码> 代替。

这也适用于数据成员:this->basefield

Using a qualified-identifier class-name::function() inhibits virtual-ness of function, so you should use this->function() instead.

This also works for data members: this->basefield.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文