在这样的声明中const的含义是什么?这个常数使我困惑。

class foobar
{
  public:
     operator int () const;
     const char* foo() const;
};

当前回答

与函数声明一起使用的const关键字指定它是一个const成员函数,它将无法更改对象的数据成员。

其他回答

当您将const关键字添加到方法时,此指针将实质上变为指向const对象的指针,因此您不能更改任何成员数据。(除非您使用mutable,否则稍后将详细介绍)。

const关键字是函数签名的一部分,这意味着您可以实现两个类似的方法,一个在对象为const时调用,另一个则不调用。

#include <iostream>

class MyClass
{
private:
    int counter;
public:
    void Foo()
    { 
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

这将输出

Foo
Foo const

在非常量方法中,可以更改实例成员,这在常量版本中是无法做到的。如果将上面示例中的方法声明更改为下面的代码,则会出现一些错误。

    void Foo()
    {
        counter++; //this works
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++; //this will not compile
        std::cout << "Foo const" << std::endl;
    }

这并不完全正确,因为您可以将成员标记为可变的,然后const方法可以更改它。它主要用于内部计数器等。解决方案是以下代码。

#include <iostream>

class MyClass
{
private:
    mutable int counter;
public:

    MyClass() : counter(0) {}

    void Foo()
    {
        counter++;
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++;    // This works because counter is `mutable`
        std::cout << "Foo const" << std::endl;
    }

    int GetInvocations() const
    {
        return counter;
    }
};

int main(void)
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
    std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}

它将输出

Foo
Foo const
Foo has been invoked 2 times

这里const表示在该函数中任何变量的值都不能改变

class Test{
private:
    int a;
public:
    void test()const{
        a = 10;
    }
};

像这个例子一样,如果你试图改变测试函数中变量的值,你会得到一个错误。

这些常量意味着如果“with const”方法更改内部数据,编译器将出错。

class A
{
public:
    A():member_()
    {
    }

    int hashGetter() const
    {
        state_ = 1;
        return member_;
    }
    int goodGetter() const
    {
        return member_;
    }
    int getter() const
    {
        //member_ = 2; // error
        return member_;
    }
    int badGetter()
    {
        return member_;
    }
private:
    mutable int state_;
    int member_;
};

测试

int main()
{
    const A a1;
    a1.badGetter(); // doesn't work
    a1.goodGetter(); // works
    a1.hashGetter(); // works

    A a2;
    a2.badGetter(); // works
    a2.goodGetter(); // works
    a2.hashGetter(); // works
}

阅读此处了解更多信息

const表示该方法承诺不会更改类的任何成员。即使对象本身被标记为const,也可以执行如此标记的对象成员:

const foobar fb;
fb.foo();

将是合法的。

看看C++中“const”的用法有多少?了解更多信息。

与函数声明一起使用的const关键字指定它是一个const成员函数,它将无法更改对象的数据成员。