C函数调用C ++类命名空间

时间:2012-11-24 20:32:43

标签: c++ system-calls

我试图通过一个项目来熟悉C ++,但是我遇到了一个错误,我不太清楚如何处理。我有以下代码:

void myclass::write(std::string str) {
  write(filedes, (void *)str.c_str(), str.length());
}

其中filedes是myclass的实例变量。试图编译它会产生错误:

myclass.cpp: In member function ‘void myclass::write(std::string)’:
myclass.cpp:38: error: no matching function for call to ‘myclass::write(int&, void*, size_t)’
myclass.cpp:37: note: candidates are: void myclass::write(std::string)
myclass.hpp:15: note:                 void myclass::write(std::string, int)

那么我做错了什么?我可以合法地从方法中调用此函数吗?

5 个答案:

答案 0 :(得分:4)

据推测,您想要调用write(2),它位于全局命名空间中:

::write(filedes, str.c_str(), str.length());

(您可能需要#include <unistd.h>)。

答案 1 :(得分:0)

看起来编译器不知道全局write函数。你是否在unix中包含了正确的标题(<unistd.h>)? (另外,(void *)演员阵容无用。)

答案 2 :(得分:0)

filedes不是类的实例变量(不是类的实例),而是类型为int的类的成员,正如我从编译器错误中看到的那样。如果要从全局命名空间调用函数,并使用与其中的方法相同的名称,请使用:: write(...)。顺便说一句:使用std :: size_t作为长度,而不是int。

答案 3 :(得分:0)

编译器认为write是你的类方法,它不是。如果你在谈论系统调用写,你应该#include unistd.h并使用:: write(filedes,(void *)str.c_str(),str.length());

答案 4 :(得分:0)

它取决于写入函数是什么,如果它是一个系统函数,那么你必须使用它 :: write,如果它在其他一些代码中确保你把extern,使用标题或实现该函数的代码