使用基类指针访问派生类(正向声明)



如何从下面的场景访问我的单元测试框架(即Gtest_main.cpp(中的派生类成员变量。

imp.cpp

class base{
public:
virtual void foo()=0;
};

class derived : public base{
public:
int abc; // how to access this from Gtest_main.cpp
void foo(){
std::cout<<"This is derived foo() n";
}
}; 
//Unit test framework call on createPlugin to get instance of derived class
void createPlugin(base **plugin){
derived *dp = new derived;
*plugin=dp;
}

Gtest_main.cpp(单元测试文件(

class derived //forward declaration 
base *p;
createPlugin(&p);
static_cast<derived*>(p)->abc=9090; //error how to access abc?

如何访问Gtest_main.cpp中的abc。请注意,我无法修改原始源代码impl.cpp

如何在Gtest_main.cpp 中访问abc

你不能。如果没有看到类derived的完整定义,编译器就不知道derived::abc的含义。

最新更新