I am writing an application in c++. I have an interface defined with various functions:
class ITest
{
public:
virtual void x()=0;
virtual void y()=0;
}
I then have a class t开发者_JAVA技巧hat implements this interface, along with additional functions:
class NewClass: public ITest
{
public:
virtual void x();
virtual void y();
// new function not defined in interface
virtual void z();
}
I now want to access all of these 3 functions from my unit tests. Currently I am using:
ITest* pTest;
which will only give me access to the 2 functions defined in the interface. How can I also gain access to function z() without defining it in the interface?
NewClass* p = dynamic_cast<NewClass*>(pTest);
if(p==0)
{
//error!!! pTest's dynamic type wasn't NewClass*
}
else
{
p->z();
}
Instead of dynamic_cast
, you can use static_cast
. But if pTest
's dynamic type is not actually NewClass*
you'll get undefined behavior.
Use a NewClass* or cast to one if it is one.
As it is an unit test, you control the line where the class is created.
Now don't do:
ITest* pTest = new NewClass();
but do:
NewClass* pTest = new NewClass();
and you can use pTest->z()
without problems.
精彩评论