gpt4 book ai didi

c++ - "this"指针是否启用了 RTTI?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:18 24 4
gpt4 key购买 nike

我试图在对象的继承树中的其中一个类的构造函数中发现对象的派生程度最高的类。我现在已经在这上面花了几个小时,并且不知道我还能怎么做或者为什么它没有意义。这似乎很有道理,但它拒绝工作。我找到了很多关于 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 是否出于某种我还无法想象的原因从“this”中剥离了?这如何不破坏虚函数的想法?(我用虚函数实现了这个,直到我发现我正在重新实现 RTTI 的一部分,这是我以前不知道的。)如输出所示,我可以如果我避免使用“this”,它就可以正常工作,但这样做的需要似乎是设计使然。

最佳答案

你不能那样做,因为你误解了所涉及的动态。

规则是:

The this in constructor/destructor of any class points to the class whose constructor/destructor it is.

此外,这也是在构造函数中调用的 virtual 函数在使用动态调度时不像您通常期望的 virtual 函数那样工作的原因。

您应该在调用构造函数后检测类型。您可以在除构造函数和析构函数之外的任何成员函数中执行此操作。

关于c++ - "this"指针是否启用了 RTTI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11113486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com