C++ 非成员函数不能有 cv 限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10982628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
non-member function cannot have cv-qualifier
提问by A. K.
While writing the following function abs
, I get the error:
在编写以下函数时abs
,出现错误:
non-member function unsigned int abs(const T&)
cannot have cv-qualifier.
非成员函数unsigned int abs(const T&)
不能有 cv 限定符。
template<typename T>
inline unsigned int abs(const T& t) const
{
return t>0?t:-t;
}
After removing the const
qualifier for the function there is no error. Since I am not modifying t
inside the function the above code should have compiled. I am wondering why I got the error?
删除const
函数的限定符后,没有错误。因为我没有t
在函数内部修改,所以上面的代码应该已经编译了。我想知道为什么我收到错误?
回答by Attila
Your desire not to modify t
is expressed in const T& t
. The ending const
specifies that you will not modify any member variable of the class abs
belongs to.
您不想修改的愿望以t
表示const T& t
。结尾const
指定您不会修改该类abs
所属的任何成员变量。
Since there is no class where this function belongs to, you get an error.
由于没有这个函数所属的类,你会得到一个错误。
回答by Bo Persson
The const
modifier at the end of the function declaration applies to the hidden this
parameter for member functions.
const
函数声明末尾的修饰符适用this
于成员函数的隐藏参数。
As this is a free function, there is no this
and that modifier is not needed.
由于这是一个免费功能,因此没有this
并且不需要该修饰符。
The t
parameter already has its own const
in the parameter list.
该t
参数已const
在参数列表中拥有自己的参数。
回答by ecatmur
The cv-qualifier on a member function specifies that the this
pointer is to have indirected type const
(or volatile
, const volatile
) and that therefore the member function can be called on instances with that qualification.
成员函数上的 cv 限定符指定this
指针具有间接类型const
(或volatile
, const volatile
),因此可以在具有该限定的实例上调用成员函数。
Free functions (and class static functions) don't have a this
pointer.
自由函数(和类静态函数)没有this
指针。
回答by Xiaofeng.Wang
As we all know, const
keyword followed after the argument list indicates that this is a pointer to a pointer constant.
众所周知,const
参数列表后面的关键字表示这是一个指向指针常量的指针。
There is a non-member function, it does not belong to the class, so add const opposite end error occurs.
有一个非成员函数,它不属于类,所以添加const相反端会出现错误。
Solution to the problem:is to either become a class member function or remove the const
keyword const opposite end
问题的解决方法:要么变成类成员函数,要么去掉对const
端的关键字const