首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++中关于判断一个类是否继承于另外一个类的方法?该如何处理

2012-03-04 
C++中关于判断一个类是否继承于另外一个类的方法?Class A{Public:Virtual void function(){}}Class B:publ

C++中关于判断一个类是否继承于另外一个类的方法?
Class A
{
Public:
Virtual void function(){}
}

Class B:public class A
{
Public:
Virtual void function(){}
}

Class C:public class B
{
Public:
Virtual void function(){}
}

C* p=new C;
我现在运行时刻判断C类是否继承于B或则A,应该怎么在C++中实现?比如说,我有下面这个函数
IsDerivedFrom(C,A),这样的功能应该怎么实现?


[解决办法]

C/C++ code
#include<iostream>using namespace std;class A { public: virtual void function(){} } ;class B:public  A { public: virtual void function(){} } ;class C:public  A { public: virtual void function(){} } ;void   main() {     C* p=new C;    try    {        B* s = dynamic_cast<B*>(p);        cout <<"OK"<<endl;    }    catch(...)    {        cout<<"NOT OK"<<endl;    }}
[解决办法]
Loki库里有方法的,google: Loki, c++。参考一本书,中文名叫《编程新思维,C++范型编程与设计模式》,是Loki的作者的论文集。不过这样的技巧属于范型编程,很难理解。运行中可以用dynamic_cast,例如:

A* a;
....

if (C* cp=dynamic_cast<C*>(a))
{
//it is sure that C is derived from A, or C & A are the same type
}

[解决办法]
struct Small { char c; };
struct Big { small s[2]; };

Small ISA(...);
Big ISA(A*);

template <class C, class A>
struct IsDrivedFrom
{
enum { RET = (sizeof(ISA(new C)) == sizeof(Big)) );
}

[解决办法]
#include <iostream>
using namespace std;

template <int n>
struct Tag { Tag<n-1> x[2]; };

template <>
struct Tag<0> { char c; };

#define CheckMember(RES,TC,VN,VT)\
struct RES\
{\
struct Flag {};\
static Flag* VN;\
\
struct HasMemberHelper : public TC\
{\
Tag<0> check(Flag*);\
Tag<1> check(...);\
Tag<2> check(VT &);\
int helper()\
{\
return sizeof(check(VN));\
}\
static int Result()\
{\
HasMemberHelper f;\
return f.helper();\
}\
};\
static int result() { return HasMemberHelper::Result(); }\
};

void explain_result(int r)
{
if(r == sizeof(Tag<0>))
{
cout << "Test class has no member named foo.";
}
else if(r == sizeof(Tag<1>))
{
cout << "Test class has member named foo but type is mismatch.";
}
else if(r == sizeof(Tag<2>))
{
cout << "Test class has member named foo and type is match also.";
}
cout << endl;
}


//-----------------------------------------------
// 定义三个测试类
struct TestA
{
int foo;
};

struct TestB
{
char foo;
};

struct TestC
{
int woo;
};

//-----------------------------------------------
// 检查给定的测试类是否含有名为foo的成员变量.
// 并且类型是否为int
CheckMember(DoesTestAHasMemberFoo, TestA, foo, int);
CheckMember(DoesTestBHasMemberFoo, TestB, foo, int);
CheckMember(DoesTestCHasMemberFoo, TestC, foo, int);


int main()
{
int r;

cout << "Check TestA:" << endl;
r = DoesTestAHasMemberFoo::result();
explain_result(r);

cout << "Check TestB:" << endl;
r = DoesTestBHasMemberFoo::result();
explain_result(r);

cout << "Check TestC:" << endl;


r = DoesTestCHasMemberFoo::result();
explain_result(r);

return 0;
}

热点排行
Bad Request.