const这些声明中的含义是什么?该const混淆了我.
class foobar
{
public:
operator int () const;
const char* foo() const;
};
Run Code Online (Sandbox Code Playgroud) 在编写以下函数时abs,我收到错误:
非成员函数unsigned int abs(const T&)不能有cv-qualifier.
template<typename T>
inline unsigned int abs(const T& t) const
{
return t>0?t:-t;
}
Run Code Online (Sandbox Code Playgroud)
删除const函数的限定符后,没有错误.由于我没有t在函数内部进行修改,因此上面的代码应该编译.我想知道为什么我得到错误?
可能重复:
const表示函数/方法签名后的含义是什么?
我在C++的后期阅读中遇到了很多函数(特别是在Boost上),它有一个我以前从未见过的符号.例如:
virtual void B() const;
Run Code Online (Sandbox Code Playgroud)
你可以看到我们在函数名后面有一个const!我已经看到const关键字主要是关于它们在函数中使用的函数返回值(或作为参数),但是这个是不同的.任何人都可以向我解释它是什么以及为什么我们使用它?还有什么不同于常规使用const函数?
int * const Function(int *const constantPointerToAnInteger, char const* pointerToAConstantChar);
Run Code Online (Sandbox Code Playgroud) 可能重复:
const表示函数/方法签名后的含义是什么?
继续笑我,但函数后的const表示什么?
int someFunc() const{ //<<----notice the const
//insert code blah...
}
Run Code Online (Sandbox Code Playgroud)
如果我想要返回类型的const int,我不会写
const int someFunc(){
//code....
}
Run Code Online (Sandbox Code Playgroud)