在这样的声明中const的含义是什么?这个常数使我困惑。
class foobar
{
public:
operator int () const;
const char* foo() const;
};
在这样的声明中const的含义是什么?这个常数使我困惑。
class foobar
{
public:
operator int () const;
const char* foo() const;
};
当前回答
与函数声明一起使用的const关键字指定它是一个const成员函数,它将无法更改对象的数据成员。
其他回答
const表示该方法承诺不会更改类的任何成员。即使对象本身被标记为const,也可以执行如此标记的对象成员:
const foobar fb;
fb.foo();
将是合法的。
看看C++中“const”的用法有多少?了解更多信息。
我想补充一点。
也可以将其设置为常量和常量&&
So,
struct s{
void val1() const {
// *this is const here. Hence this function cannot modify any member of *this
}
void val2() const & {
// *this is const& here
}
void val3() const && {
// The object calling this function should be const rvalue only.
}
void val4() && {
// The object calling this function should be rvalue reference only.
}
};
int main(){
s a;
a.val1(); //okay
a.val2(); //okay
// a.val3() not okay, a is not rvalue will be okay if called like
std::move(a).val3(); // okay, move makes it a rvalue
}
请随意改进答案。我不是专家
与函数声明一起使用的const关键字指定它是一个const成员函数,它将无法更改对象的数据成员。
C++公共知识:基本中级编程中Const成员函数的含义给出了明确的解释:
类的非常量成员函数中此指针的类型X是X*常量。也就是说,它是指向非常数X的常数指针(见Const Pointers和Pointers to Const[7,21])。因为对象它所指的不是常量,可以修改。类型这在类X的常量成员函数中是常量X*const。那个是,它是指向常量X的常量指针。因为它是常量,不能修改。这就是常量和非常量成员函数之间的差异。
因此,在您的代码中:
class foobar
{
public:
operator int () const;
const char* foo() const;
};
你可以这样想:
class foobar
{
public:
operator int (const foobar * const this) const;
const char* foo(const foobar * const this) const;
};
这里const表示在该函数中任何变量的值都不能改变
class Test{
private:
int a;
public:
void test()const{
a = 10;
}
};
像这个例子一样,如果你试图改变测试函数中变量的值,你会得到一个错误。