c++ - 是否可以从父类 "this"指针类型强制转换为子类

标签 c++ c++11 c++14

我需要从父类成员函数访问子类变量。

我尝试在父类 this 指针上动态转换为子类,但出现以下编译错误:

> main.cpp: In member function ‘void Parent::do_something()’:
  main.cpp:24:45: error: cannot dynamic_cast ‘(Parent*)this’ (of type ‘class Parent*’) to type ‘class Child*’ (target is not pointer or reference to complete type)
     Child *child = dynamic_cast<Child*>(this);

有什么办法可以达到我的要求。

#include <iostream>

using namespace std;

class Child;

class Parent {
    public:
    Parent() {};
    virtual ~Parent() {};
    void do_something();
};

void Parent::do_something()
{
    Child *child = dynamic_cast<Child*>(this);
    child->i = 10;
}

class Child : public Parent {
    public:
    int i = 0;
    void do_something() {}
    void do_something1() 
    {
        Parent *parent = static_cast<Child*>(this);
        parent->do_something();
    }
};

int main()
{
    Child child;
    child.do_something1();
    printf ("Value of i: %d", child.i);

    return 0;
}

最佳答案

错误消息的重要部分是这样的:

target is not pointer or reference to complete type

[强调我的]

您需要 Child 类的完整定义才能工作。

解决方案是重新安排您的代码,以便在 Child 类定义之后定义(实现)do_something 函数:

class Child : public Parent { ... };

void Parent::do_something() { ... }

关于c++ - 是否可以从父类 "this"指针类型强制转换为子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57457738/

相关文章:

c++ - 保存 wxWidgets 窗口截图

c++ - Boost.Asio SSL线程安全

c++ - 从抽象类的指针 vector 调用函数

c++ - 将持续时间添加到 C++ 时间点

string - 输出此字符串序列的第 n 遍

c++ - 为什么命名空间中的函数看不到我全局定义的 operator<<?

c++ - 矩阵和变换可以互换吗?

异常情况下的 C++ 错误 C2228( '.val' 左侧必须有类/结构/union )

C++ 如何使用 std::bind/std::function 引用模板函数

c++ - 语句 block 的原子执行