范围界定运算符是否会改变幕后发生的事情?

发布于 2024-12-01 07:31:48 字数 630 浏览 3 评论 0原文

我这里有一种情况 - 基本上:

#include <iostream>

class A {
    public:
        virtual void foo()=0;
};

class B : A {
    public:
        void foo() { cout << "I hate this code." << endl; }
        void DoSomething() { /* Code */ }
};

在我的情况下,A和B位于不同的文件中,而且不用说,更复杂 - 但这是我的问题:

在函数中的类B内的某个地方(例如DoSomething()),我调用富。现在, foo 是来自 A 的纯虚函数,在 B 中正确定义,因此它工作正常 - 编译也很好。

如果我这样称呼它:

B::foo()

效果很好。

如果我这样称呼它:

foo()

它在运行时挂起系统。当函数不是静态或类似的东西时,为什么作用域运算符会改变结果?

PS:我当场编写了该代码,并且没有针对此问题的编译器,如果有任何拼写错误,请抱歉。

I have a situation here - basically:

#include <iostream>

class A {
    public:
        virtual void foo()=0;
};

class B : A {
    public:
        void foo() { cout << "I hate this code." << endl; }
        void DoSomething() { /* Code */ }
};

A and B are in different files in my case, and much more complex needless to say - but here is my problem:

Somewhere within the class B in a function (like DoSomething()), I call foo. Now, foo is a pure-virtual function from A properly defined in B, so it works fine - the compilation is fine too.

If I call it like:

B::foo()

it works great.

If I call it like:

foo()

It hangs the system at run time. Why would scoping operators change the outcome when the function is not static or anything like that anyway?

PS: I wrote that code on the spot and didn't have a compiler for this question, so sorry for typos if there are any.

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

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

发布评论

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

评论(1

过期情话 2024-12-08 07:31:48

代码看起来是正确的。这强烈暗示 vptr 或 vtable 已被某些越界内存访问损坏,或者 this 指针无效。

作用域运算符通过允许它完全绕过虚拟函数查找来更改调用。

The code looks correct. This strongly implies that the vptr or vtable have been corrupted by some out-of-bounds memory access, or that the this pointer is invalid.

The scoping operator changes the call by allowing it to bypass the virtual function lookup altogether.

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