本文介绍了未按预期调用 C++ 虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在摆弄虚拟方法的正确覆盖.我链接了一些构造函数,并在基类构造函数中调用了一个虚方法.
I'm fiddling around with proper overriding of virtual methods. I chain some constructors and in the base class constructor I call a virtual method.
调用链应该如下:
B(p)->A(p)->B.foo(p)
调用链在 C++ 中:
Call chain is in C++:
B(p)->A(p)->A.foo(p)
调用链在 C# 中:
B(p)->A(p)->B.foo(p)
换句话说,在 C# 中的行为就像预期的那样,而在 C++ 中则不然.
So in other words, in C# behaviour is like expected, in C++ it isn't.
C++ 代码:
#include <cstdio>
class A {
public:
A();
A(int);
virtual void foo(int s);
};
class B : public A {
public:
B();
B(int s) : A(s) {};
virtual void foo(int s) override;
};
A::A() {
std::printf("A\r\n");
};
A::A(int s) : A() {
std::printf("A: %d\r\n", s);
foo(s);
};
void A::foo(int s) {
std::printf("A::foo(%d)\r\n", s);
}
B::B() : A(){
std::printf("B\r\n");
};
void B::foo(int s) {
std::printf("B::foo(%d)\r\n", s);
}
int main(int argc, char* argv[]) {
B b(2);
}
输出:
A
A: 2
A::foo(2)
C# 代码:
using System;
namespace demo {
class A{
public A() {
Console.WriteLine("A");
}
public A(int s) : this(){
Console.WriteLine("A: " + s.ToString());
foo(s);
}
public virtual void foo(int s) {
Console.WriteLine(string.Format("A:foo({0})", s));
}
}
class B : A{
public B() : base() {
Console.WriteLine("B");
}
public B(int s) : base(s) {
}
public override void foo(int s) {
Console.WriteLine(string.Format("B:foo({0})", s));
}
}
static class Run {
static void Main() {
new B(2);
}
}
}
输出:
A
A: 2
B::foo(2)
为什么在 C++ 中没有调用 B 类的重写方法?我该如何正确覆盖它?
Why isn't the overriden method of class B called in C++? How do I have to override it correctly?
推荐答案
这就是 C++ 的工作方式.虚函数在对象构造和销毁过程中不会虚拟地运行.
This is just the way C++ works. Virtual functions do not behave virtually during object construction and destruction.
这篇关于未按预期调用 C++ 虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!