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

一个虚函数的简单有关问题,大家来讨论下哈

2012-05-03 
一个虚函数的简单问题,大家来讨论下哈class BOOL_FUN_LPWSTR{public:virtual bool exclude(){return 1}pr

一个虚函数的简单问题,大家来讨论下哈
class BOOL_FUN_LPWSTR 
{
public:
virtual bool exclude(){return 1;}
protected:
private:
};

class VOID_FUN : public BOOL_FUN_LPWSTR
{
public:
virtual bool exclude(){return 0;}
protected:
private:
};

int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
if (i == 0)
{
typedef BOOL_FUN_LPWSTR type;
}
else if (i == 1)
{
typedef VOID_FUN type;
}
BOOL_FUN_LPWSTR *parent;
type aa;
parent = &aa;
parent->exclude();
aa.exclude();
return 0;
}
我的目的是想通过i的不同分别定义不同的对象,然后通过基类指针实现不同的接口,可是这样的话,type aa;这句话就不对了,因为type的作用域问题,type aa;的type是不识别的类型,如果才能做到迟绑定呢?

[解决办法]
typedef 定义的类型是有 作用域的,这也是typedef和#define的区别之一。
[解决办法]

C/C++ code
int _tmain(int argc, _TCHAR* argv[]){    int i = 0;#if i#define type BOOL_FUN_LPWSTR#else#define type VOID_FUN#endif    BOOL_FUN_LPWSTR *parent;    type aa;    parent = &aa;    parent->exclude();    aa.exclude();    return 0;}
[解决办法]
探讨
C/C++ code


int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;

#if i
#define type BOOL_FUN_LPWSTR
#else
#define type VOID_FUN
#endif

BOOL_FUN_LPWSTR *parent;

type aa;
……

[解决办法]
可能系统对于无法处理的i,将其看成逻辑值为0,这样#define type VOID_FUN就被定义了。另外typedef 定义的类型确实是有作用域,但是严格来说#define定义的宏也有作用域啊,只不过他的作用域不同寻常,影响范围为从他定义到#undef xxx或到文件尾

热点排行