C++ 类成员函数命名规则
我正在尝试将 C 套接字库中的一些函数封装到我自己的 C++ 类中。 我想定义一个成员函数,它使用与其相应的 C 函数相同的名称,但具有不同的签名。 例如,我想编写
ssize_t MyClass::write(const void *buf);
一个调用的
ssize_t write(int fd, const void *buf, size_t count);
函数,当我编译时,出现以下错误
error: no matching function for call to ‘MyClass::write(int&, const char*&, size_t)’
note: candidates are: ssize_t MyClass::write(const char*)
我有正确的#include
语句来调用C套接字库,但是我的写函数的定义似乎掩盖了它。 如果我将类定义函数的名称更改为其他名称,则一切似乎都工作正常。
我相当确定更改函数名称将是我的最终解决方案,但是有人可以告诉我导致此行为的 C++ 命名规则的名称吗? 我想读一下它,这样我就知道我将来要做什么。
I'm trying to encapsulate some functions from the C socket library into my own C++ class. I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature. For example, I'd like to write the function
ssize_t MyClass::write(const void *buf);
which makes a call to
ssize_t write(int fd, const void *buf, size_t count);
When I compile I get the following errors
error: no matching function for call to ‘MyClass::write(int&, const char*&, size_t)’
note: candidates are: ssize_t MyClass::write(const char*)
I have the correct #include
statements to make the call to the C socket library, but my definition of a write function seems to be shadowing it. If I change the name of my class defined function to something else, everything seems to work fine.
I'm reasonably sure that changing my function name is going to be my final solution, but could someone tell me the name of the C++ naming rule that causes this behavior? I'd like to read up on it so I know what I'm doing in the future.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过调用 C 函数,明确它位于全局命名空间中,例如 ::write?
Have you tried calling the C function expliciting that it lives in the global namespace, like ::write?
此页面很好地描述了C++ 中的名称查找规则。 基本上,一旦编译器发现 write() 是一个类成员函数,它就不会查找同名的全局函数。 然后它会报告一个错误,因为成员函数
write()
没有您所提供的正确数量和类型的参数。 使用一元作用域解析运算符::
会强制编译器仅在全局命名空间中搜索名为write()
的函数,然后搜索就会成功。This page does a pretty good job of describing the name lookup rules in C++. Basically, once the compiler sees that
write()
is a class member function, it doesn't look for global functions of the same name. It then reports an error since the member functionwrite()
doesn't have the right number and types of arguments as what you gave it. The use of the unary scope resolution operator::
forces the compiler to only search the global namespace for functions namedwrite()
, which then succeeds.更一般地,当编译器查找函数时,它首先在最近的命名空间中查找,如果找到具有正确名称的函数,则即使签名不匹配,它也不会再查找。
More generally, when the compiler goes looking for a function, it looks in the closest namespace first, and if it finds one with the correct name, it doesn't look any further, even if the signatures don't match.