我正在尝试在继承树中的一个类的构造函数中,发现对象的最派生类。我已经花了几个小时来解决这个问题,但是我无法弄清楚该怎么做或者为什么它不起作用。它似乎是完全合理的,但是它拒绝工作。我已经找到了很多关于RTTI的页面,但基本上没有得到任何有用的信息。在我的测试案例及其输出之后,我将继续解释。
输出结果(在g++上):
我正在尝试将输出的第二行从“1A”更改为“1B”。我不能想象为什么“this”上的RTTI会被剥离?这不会破坏虚函数的概念吗?(在我发现我正在重新实现RTTI的一部分之前,我已经使用虚函数实现了这个功能,但我以前不知道)。正如输出所示,如果我避免使用“this”,那么我可以使其工作,但是需要这样做似乎就像是设计上的问题。
#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)
我正在尝试将输出的第二行从“1A”更改为“1B”。我不能想象为什么“this”上的RTTI会被剥离?这不会破坏虚函数的概念吗?(在我发现我正在重新实现RTTI的一部分之前,我已经使用虚函数实现了这个功能,但我以前不知道)。正如输出所示,如果我避免使用“this”,那么我可以使其工作,但是需要这样做似乎就像是设计上的问题。