简体   繁体   中英

C function calls in C++ class namespace

I'm attempting to familiarize myself with C++ by way of a project, but I have hit an error that I am not quite sure how to deal with. I have the following code:

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

Where filedes is an instance variable of myclass. Attempting to compile this yields the error:

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)

So what am I doing wrong? Can I not legally make this function call from the method?

Presumably you want to call write(2) , which is in the global namespace:

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

(you might need to #include <unistd.h> ).

It looks like the compiler isn't aware of a global write function. Did you include the right headers ( <unistd.h> in unix)? (Also, that (void *) cast is useless.)

filedes is not an instance variable of your class (not an instance of your class), but a member of your class with type int, as I see from the compiler error. If you want to call a function from a global namespace with the same name as a method there, use ::write(...). By the way: Use std::size_t for length, not int.

Compiler thinks that write is your class method and it isnt. If you are talking about system call write you should #include unistd.h and use ::write(filedes, (void *)str.c_str(), str.length());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM