2015-11-03 97 views
0

我使用的是C libtrary与调用成员C++的功能,但C函数具有相同的名称

#define read _io_read 

,但我有一个C++类继承的成员函数“读”。 我想从另一个成员函数调用成员函数,但编译器认为我想调用全局作用域中的C函数 。

我尝试以下

//header 
    namespace myNameSpace{ 
     class B : public A{ 
     int read(); 
     int do_read(); 
    } 
    } 

//cpp 
using namespace myNameSpace; 
int B::read(){ 
//other code needed 
_io_read(); 
} 

int B::do_read(){ 
this.read(); // here is where compiler resolves to _io_read 
} 

有没有去解决这个?我宁愿不重命名基类A的读取函数,因为我无法更改不是我的代码。

TIA

+5

一个'#define'是从“在全球范围内的C函数”非常不同的,所以你问你的问题的方式引起误解。你应该编辑它。 '#define'适用于所有范围规则之前。所以,无论你如何使用'#define',都是编写糟糕的C代码,这是非常糟糕的C++代码。但是,如果你坚持使用包含那个写得不好的.h文件,你需要处理它(可能用'#undef') – JSF

+1

这就是为什么'#define'得到一个坏名字的原因。你需要知道'#undef'。 –

+0

任何试图将'read'这样的通用术语定义的任何人都应该被解雇。 – PaulMcKenzie

回答

2

你可以使用:

int B::do_read(){ 
#undef read 
this.read(); // here is where compiler resolves to _io_read 
#define read _io_read 
} 
+0

我已经将#undef添加到.cpp文件的开头,它工作正常。如果我需要调用C函数,我直接调用它作为_io_read。 谢谢! –

0

我会修改回答说:在你的模块,你可以重新定义所有违规的#define较少模棱两可的东西。例如,如果#define的C例程从libquux,您可以编辑quux.h重新定义他们:

/*#define read _io_read*/ 
#define quux_read _io_read 

唉,你有普通CPP没有更好的微距能力。

0

我将它放在.cpp文件的开头,并且将删除不再需要的名称空间。对不起,描述的#define作为全球范围内,还在学习正确的术语:)

#ifdef read 
#undef read 
#endif 

int B::read(){ 
//other code needed 
_io_read(); //call C function directly 
} 

int B::do_read(){ 
this.read(); //no more problem here 
} 
相关问题