我需要从父类成员函数访问子类变量。
我尝试在父类 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/