类命名空间中的 C 函数调用C++
C function calls in C++ class namespace
我试图通过一个项目来熟悉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)
那我做错了什么呢?我可以合法地从方法进行此函数调用吗?
大概你想调用 write(2)
,它在全局命名空间中:
::write(filedes, str.c_str(), str.length());
(您可能需要#include <unistd.h>
)。
看起来编译器不知道全局write
函数。您是否包含正确的标头(在 unix 中<unistd.h>
)?(另外,(void *)
演员表是没有用的。
filedes 不是类的实例变量(不是类的实例),而是类型为 int 的类的成员,正如我从编译器错误中看到的那样。如果要从与那里的方法同名的全局命名空间调用函数,请使用 ::write(...)。顺便说一下:使用 std::size_t 表示长度,而不是 int。
编译器
认为write是你的类方法,但事实并非如此。如果你在谈论系统调用写入,你应该 #include unistd.h并使用::write(filedes, (void *)str.c_str(), str.length());
这取决于写入函数是什么,如果它是一个系统函数,那么你必须使用::write ,如果它是在其他代码中,请确保输入 extern,使用标头或实现函数的代码
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销