[英]C++ class member function naming rules
I'm trying to encapsulate some functions from the C socket library into my own C++ class. 我正在尝试将C套接字库中的一些函数封装到我自己的C ++类中。 I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature.
我想定义一个成员函数,它使用与其相应的C函数相同的名称,但具有不同的签名。 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. 我有正确的
#include
语句来调用C套接字库,但是我对write函数的定义似乎正在影响它。 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? 我有理由相信,更改我的函数名称将成为我的最终解决方案,但有人可以告诉我导致此行为的C ++命名规则的名称吗? I'd like to read up on it so I know what I'm doing in the future.
我想阅读它,所以我知道我将来在做什么。
您是否尝试过调用C函数来解释它是否存在于全局命名空间中,例如:: write?
This page does a pretty good job of describing the name lookup rules in C++. 这个页面在描述C ++中的名称查找规则方面做得非常好。 Basically, once the compiler sees that
write()
is a class member function, it doesn't look for global functions of the same name. 基本上,一旦编译器发现
write()
是类成员函数,它就不会查找同名的全局函数。 It then reports an error since the member function write()
doesn't have the right number and types of arguments as what you gave it. 然后报告错误,因为成员函数
write()
没有正确的数量和类型的参数。 The use of the unary scope resolution operator ::
forces the compiler to only search the global namespace for functions named write()
, which then succeeds. 使用一元范围解析运算符
::
强制编译器仅搜索名为write()
函数的全局命名空间,然后成功。
更一般地说,当编译器寻找函数时,它首先查找最近的命名空间,如果找到具有正确名称的命名空间,即使签名不匹配,它也不会再查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.