我试图在其继承树中的一个类的构造函数中发现一个对象的派生类最多的类.我现在已经花了几个小时在这上面,我不知道我怎么做,或者为什么它没有意义.它似乎很有道理,但却拒绝工作.我找到了很多关于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;
}
Run Code Online (Sandbox Code Playgroud)
输出(在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)
Run Code Online (Sandbox Code Playgroud)
我试图让输出的第二行说"1B"而不是"1A".由于某种原因我无法想象RTTI是否被剥离了"this"?这怎么不打破虚函数的想法?(我用虚函数实现了这个,直到我发现我重新实现了RTTI的一部分,我以前不知道.)正如输出所示,如果我避免使用"this",我可以使这个工作,但需要这看起来像设计破坏.
你不能这样做,因为你误解了所涉及的动态。
规则是:
任何类的构造函数
this/析构函数都指向其构造函数/析构函数所属的类。
virtual此外,这也是构造函数中调用的函数的行为与您在使用动态分派时通常期望的virtual函数工作方式不同的原因。
您应该在调用构造函数之后检测类型。您可以在除构造函数和析构函数之外的任何成员函数中执行此操作。