c++ - 'const'最后在类的函数声明中的含义?

标签 c++ constants declaration c++-faq

const 在这样的声明中是什么意思? const 让我很困惑。

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

最佳答案

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

const 关键字是函数签名的一部分,这意味着您可以实现两种类似的方法,一种在对象为 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

在非常量方法中,您可以更改实例成员,而在 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;
    }

这并不完全正确,因为您可以将成员标记为 mutable,然后 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

关于c++ - 'const'最后在类的函数声明中的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751681/

相关文章:

java - 是否可以在 java switch/case 语句中使用类名?

c++ - 在没有new关键字的情况下创建的c++中结构对象的范围

oracle - 绑定(bind)变量和替换变量(我使用 && 输入)有什么区别?

javascript - 在 Javascript 中单行定义数组

c++ - 换位表会不会导致搜索不稳定

c++ - 是否有 g++ 的浏览器对象/类?

c++ - 存储用于事件监听器注册的指针

c++ - 当我在 C++ 中开始调试时,Visual Studio 2015 卡住

c++ - 指向常量值的常量数组指针

php - 在不同的命名空间 php 中定义常量