我正在摆弄正确覆盖虚拟方法。我链接了一些构造函数,并在基类构造函数中调用了一个虚方法。
调用链应该如下:
B(p)->A(p)->B.foo(p)
调用链在 C++ 中:
B(p)->A(p)->A.foo(p)
调用链在 C# 中:
B(p)->A(p)->B.foo(p)
换句话说,在 C# 中的行为与预期的一样,在 C++ 中则不然。
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的重写方法?我该如何正确覆盖它?
最佳答案
这正是 C++ 的工作方式。虚函数在对象构造和销毁期间不虚拟地运行。
关于c# - C++ 虚拟方法未按预期调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41457747/