我试图在其继承树中某个类的构造函数中发现对象的最派生类。我现在已经花了几个小时在这上面,我不知道我还能怎么做,或者为什么它没有意义。这似乎很合理,但它拒绝工作。我找到了很多关于 RTTI 的页面,但基本上都没有找到。在我的测试用例及其输出之后,我将继续解释。
来源:
#include <iostream>
#include <typeinfo>
#include <string>
class A
{
public:
A(std::string foo);
virtual void bar(A* a) = 0;
};
class B : public A
{
public:
B();
virtual void bar(A* a);
};
A::A(std::string foo)
{
std::cout << "type as passed to A constructor: " << foo << " (" << this << ")" << std::endl;
std::cout << "type as determined in A constructor: " << typeid(*this).name() << " (" << this << ")" << std::endl;
}
B::B() : A(typeid(*this).name())
{
A* a = (A*)this;
std::cout << "type as determined in B constructor: " << typeid(*a).name() << " (" << this << ")" << std::endl;
this->bar(this);
}
void B::bar(A* a)
{
std::cout << "type as determined in bar: " << typeid(*a).name() << " (" << a << ")" << std::endl;
}
int main()
{
B b;
b.bar(&b);
return 0;
}
输出(在 g++ 上):
type as passed to A constructor: 1B (0x7fff5fbff910)
type as determined in A constructor: 1A (0x7fff5fbff910)
type as determined in B constructor: 1B (0x7fff5fbff910)
type as determined in bar: 1B (0x7fff5fbff910)
type as determined in bar: 1B (0x7fff5fbff910)
我试图让输出的第二行说“1B”而不是“1A”。出于某种我无法想象的原因,RTTI 是否从“这个”中剥离出来?这怎么不打破虚函数的概念呢?(我已经用虚函数实现了这个,直到我发现我正在重新实现 RTTI 的一部分,这是我以前不知道的。)如输出所示,如果我避免使用“this”,我可以完成这项工作,但需要这样做似乎是设计上的破坏。