search

Home  >  Q&A  >  body text

c++ - 成员函数如果要加const, 应该加在声明处还是定义出?

如题, 考虑一个成员函数要加const的话, 如果这个成员函数在类内定义, 当然一个const就解决问题. 但是如果希望类内声明类外定义的话, 这个const是应该加在声明处还是定义处, 或者是两个地方都要加?

另外同样的问题对于inline, c++ primer上说inline在声明处和定义出同样有效, 但是最好加在定义出, const是否也是这样呢?

ringa_leeringa_lee2805 days ago650

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 14:20:09

    When definitions and declarations are separated, the definition needs to match the declaration.

    The const modifier affects function matching.

    In other words, int a() const and int a() are two member functions.

    When you define it outside the class, you can either add both or neither. Of course, you can also declare both. When calling, you will choose whether to call the const version based on the identity of the caller.

    iniline does not affect function matching, it specifies whether the function is expanded inline.

    reply
    0
  • Cancelreply