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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:41:57  来源:igfitidea点击:

non-member function cannot have cv-qualifier

c++templatesconst

提问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 constqualifier for the function there is no error. Since I am not modifying tinside 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 tis expressed in const T& t. The ending constspecifies that you will not modify any member variable of the class absbelongs 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 constmodifier at the end of the function declaration applies to the hidden thisparameter for member functions.

const函数声明末尾的修饰符适用this于成员函数的隐藏参数。

As this is a free function, there is no thisand that modifier is not needed.

由于这是一个免费功能,因此没有this并且不需要该修饰符。

The tparameter already has its own constin the parameter list.

t参数已const在参数列表中拥有自己的参数。

回答by ecatmur

The cv-qualifier on a member function specifies that the thispointer 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 thispointer.

自由函数(和类静态函数)没有this指针。

回答by Xiaofeng.Wang

As we all know, constkeyword 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 constkeyword const opposite end

问题的解决方法:要么变成类成员函数,要么去掉对const端的关键字const