【问题标题】:Why the appended const at the end of this function definition? [duplicate]为什么在这个函数定义的末尾附加 const ? [复制]
【发布时间】:2014-02-20 06:32:50
【问题描述】:

正如我正在阅读的预订中所述:

"为了也能调用get(),如果我们手头只有一个指向const TextureHolder的指针或引用,我们需要提供一个const限定的重载。这个新的成员函数返回对const sf::Texture 的引用,因此调用者无法更改纹理。..."

然后作者继续提供这个重载函数定义的例子:

const sf::Texture& TextureHolder::get(...) const;

我了解,如果您有指向 const TextureHolder 的引用或指针,则无法对其进行修改。因此返回类型为const sf::Texture&

但是为什么在函数定义的末尾附加了const?那不是只有一个指向常量this的指针,所以你不能修改类成员变量吗?那么,如果我们的函数不尝试修改任何成员/对象变量,那么这样做的目的是什么?

对于好奇的,这里是完整的功能:

sf::Texture& TextureHolder::get(Textures::ID id){
    auto found = mTextureMap.find(id);
    return *found->second;
}

~~~~~~~~~~~~~

作为语言的新手,我仍然在 C++ 语言中对 const 的上百万种不同用法(我知道,有点夸张)。

【问题讨论】:

  • @juanchopanza 你是我的英雄。
  • 它强制执行const 正确性。您不能在 const 实例上调用非常量重载(或通过 const 引用或指向 const 的指针。)

标签: c++ constants


【解决方案1】:

有一个显着的区别。 const 实例将调用 const 重载,反之亦然。

class T
{
public:
    int get() const
    {
        std::cout << "const.\n";
        return 42;
    }

    int get()
    {
        std::cout << "non-const.\n";
        return 42;
    }
};

int main()
{
    const T c;
    T t;
    auto i = c.get();
    auto j = t.get();
}

【讨论】:

    【解决方案2】:

    But why the appended const at the end of the function definition? 声明一个const函数是c++语法,函数末尾的const表示这个函数不会修改这个对象的成员变量。

    Isn't that to only have a pointer to a constant this, so you cannot modify class member variables? 每次调用成员函数时,编译器都会将this 参数压入堆栈,您并没有在参数列表中声明此变量以便将其设为 const,所以这是这样做的方法。

    So what purpose does that serve if our function isn't trying to modify any member/object variables? 如果您确定您的函数不会更改成员变量,您可以将函数设为const,因为如果将来对函数进行任何更改(可能不是由您更改),它会确认更改该函数的人函数不会改变成员变量,如果改变了,可以在编译时捕捉到。

    【讨论】:

      【解决方案3】:

      您应该将this 视为传递给成员函数的附加参数。成员函数末尾的const 表示参数可以是const 限定的。如果没有 const 限定的重载,您将无法在 const 对象上调用成员函数。在重载决议期间选择适当的成员:

      sf::Texture       t = ...;
      sf::Texture const ct = ...;
      
      t.get();  // calls sf::Texture::get()
      ct.get(); // calls sf::Texture::get() const
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-02
        • 2011-03-09
        • 1970-01-01
        • 2014-11-17
        • 2011-04-06
        • 2014-06-20
        • 2015-05-29
        相关资源
        最近更新 更多