2011-08-22 106 views
23

我想在C++类中包装一个C库。对于我的C++类,我也希望这些C函数使用相同的声明:是否可以这样做?用一个类声明方法调用一个全局函数,声明相同

如果例如我有下面的情况如何区分C函数和C++函数?我想打电话给C。

extern int my_foo(int val); // 

class MyClass{ 
    public: 
    int my_foo(int val){ 
      // what to write here to use 
      // the C functions? 
      // If I call my_foo(val) it will call 
      // the class function not the global one 
    } 
} 

回答

40

使用scope resolution operator ::

int my_foo(int val){ 
    // Call the global function 'my_foo' 
    return ::my_foo(val); 
} 
+3

您忘记在代码示例中使用范围解析运算符。你现在有一个递归函数调用,导致stackoverflow上的stackoverflow :) –

+0

@Als,Bo:*叹*感谢,我多么愚蠢。 –

4
::my_foo(val); 

应该这样做。

4

使用合格的名称查找

::my_foo(val); 

这告诉你要调用的全局函数,而不是本地函数编译器。