如何从指向父项的父类型的指针中调用子函数?
class a{
public:
virtual void print(){cout << "From a" << endl;}
};
class b: public a{
public:
void print(){cout << "Form b" << endl;}
void printFunction(){cout << "Exist in b" << endl;}
};
int main() {
a* Obj = new b;
Obj->print();
Obj->printFunction();
return 0;
}
在这里,我有一个指向“ b”的类型“ a”的指针。 我想调用仅在类b中定义的“ printFunction”。
我收到此错误:
'class a'没有名为'printFunction'的成员
问题是如何使用此指针调用“ printFunction”? 或如何在此处进行强制转换?
答案 0 :(得分:5)
使用dynamic_cast
:
class a{
public:
virtual ~a(){}
virtual void print(){ cout << "From a" << endl; }
};
class b: public a{
public:
void print(){ cout << "Form b" << endl; }
void printFunction(){ cout << "Exist in b" << endl; }
};
int main() {
a* Obj = new b;
Obj->print();
b* bObj = dynamic_cast<b*>(a);
if (bObj)
bObj->printFunction();
delete a;
return 0;
}
答案 1 :(得分:0)
You could downcast using dynamic_cast conversion
class base {
public:
void print() {std::cout << "base class print";}
};
class derived : public base {
public:
void printFunction() {std::cout << "derived class print";}
};
int main() {
base* ptr_derrived = new derived();
if(Derived* d = dynamic_cast<derived*>(ptr_derived) {
std::cout << "downcast successful\n";
d->printFunction(); // safe to call
}
delete ptr_derrived;
}