【问题标题】:C function calls in C++ class namespaceC++ 类命名空间中的 C 函数调用
【发布时间】:2012-11-12 18:37:59
【问题描述】:

我正在尝试通过一个项目来熟悉 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)

那么我做错了什么?我不能合法地从方法中调用这个函数吗?

【问题讨论】:

  • 你为什么要将c_str 转换为 void*?编译器找不到您要调用的函数
  • write 系统调用将 void* 作为参数。
  • ::放在c函数之前,以确定你想要来自全局命名空间的函数...::write(filedes, (void *)str.c_str(), str.length())

标签: c++ system-calls


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        大概你想调用write(2),它在全局命名空间中:

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

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

        【讨论】:

        • 这就是我想要的!我不确定如何引用“全局命名空间”。谢谢!尽可能接受你的回答。
        【解决方案5】:

        编译器似乎不知道全局write 函数。您是否包含正确的标题(<unistd.h> 在 unix 中)? (另外,(void *) 演员也没用。)

        【讨论】:

        • 这没关系。名称查找的工作方式意味着首先找到成员函数,然后搜索停止。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 2016-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多