【问题标题】:const member function clarification needed需要说明 const 成员函数
【发布时间】:2011-04-27 14:59:36
【问题描述】:

我有点困惑为什么这段代码会编译和运行:

class A
{
private:
    int* b;
public:
    A() : b((int*)0xffffffff) {}
    int* get_b() const {return this->b;}
};

int main()
{
    A a;
    int *b = a.get_b();
    cout<<std::hex<<b<<endl;
    return 0;
}

运行此代码的输出也是FFFFFFFF... 出乎我的意料。 this-&gt;b 不应该返回 const int*,因为它在 const 成员函数中?因此return 行应该生成编译器转换错误以尝试将const int* 转换为int*

显然,我对 const 成员函数的含义的了解存在差距。 如果有人能帮助我弥合这一差距,我将不胜感激。

【问题讨论】:

    标签: c++ constants this member-functions


    【解决方案1】:

    不,成员是int* const(从 const 函数看),完全不同。

    指针是常量,不是指向的对象。

    【讨论】:

    • 对。这就解释了。所以如果 b 是 int 并且 get_b 会尝试返回 this->b 那么我会得到转换错误。对吗?
    • 如果 b 是一个 int 并且你试图返回 &b,编译器会抱怨,是的。
    【解决方案2】:

    成员函数的const 部分只是表示当this 指针(也就是调用它的对象)为const 时允许调用该函数。它与返回值无关。

    class A{
    public:
      void non_const_func(){}
      void const_func() const {}
    };
    
    int main(){
      A a;
      a.const_func(); // works
      a.non_const_func(); // works too
    
      const A c_a;
      c_a.const_func(); // works again
      c_a.non_const_func(); // EEEK! Error, object is const but function isn't!
    

    }

    【讨论】:

      【解决方案3】:

      该函数按值返回一个整数指针 - 您不能通过该值更改作为其副本的类成员,因此不会违反 const。

      【讨论】:

        【解决方案4】:

        const 放在函数声明之后告诉编译器“嘿,我保证不会修改*this!”。您的方法只是一个访问器。

        C++ FAQ LITE 18.10

        【讨论】:

          猜你喜欢
          • 2015-03-19
          • 1970-01-01
          • 1970-01-01
          • 2016-05-17
          • 1970-01-01
          • 1970-01-01
          • 2011-06-04
          • 1970-01-01
          相关资源
          最近更新 更多